最近在項目中用到lame轉(zhuǎn)碼將wav轉(zhuǎn)換成MP3格式凰浮,其中遇到了不少的坑官疲,最大的一個就是轉(zhuǎn)碼完成后泳叠, 用audioPlayer.duration獲取的時間不準(zhǔn),而且獲取的時間一直在變恢着,最后在一位大神的幫助下解決了這個問題桐愉,下面就分享下解決過程(把整個轉(zhuǎn)碼過程都說一遍)!
我從錄制開始講:
首先在錄音時要設(shè)置錄音參數(shù)記住了掰派,通道數(shù)目必須設(shè)置為2从诲,否則轉(zhuǎn)碼后聲音不對
//錄音設(shè)置
NSMutableDictionary*recordSettings = [[NSMutableDictionaryalloc]init];
//錄音格式 無法使用
[recordSettings setValue :[NSNumbernumberWithInt:kAudioFormatLinearPCM]forKey:AVFormatIDKey];
//采樣率
[recordSettings setValue :[NSNumbernumberWithFloat:11025.0]forKey:AVSampleRateKey];//44100.0
//通道數(shù)
[recordSettings setValue :[NSNumbernumberWithInt:2]forKey:AVNumberOfChannelsKey];
//線性采樣位數(shù)
//[recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
//音頻質(zhì)量,采樣質(zhì)量
[recordSettingssetValue:[NSNumbernumberWithInt:AVAudioQualityMin]forKey:AVEncoderAudioQualityKey];
接著是轉(zhuǎn)碼了注意:注意了:錄音的采樣率和轉(zhuǎn)碼的采樣率必須一樣 必須一樣
- (void)audio_PCMtoMP3
{
NSString*mp3FileName = [self.audioFileSavePathlastPathComponent];
mp3FileName = [mp3FileNamestringByAppendingString:@".mp3"];
NSString*mp3FilePath = [self.audioTemporarySavePathstringByAppendingPathComponent:mp3FileName];
@try{
intread, write;
FILEFILE*pcm = fopen([self.audioFileSavePathcStringUsingEncoding:1],"rb");//source 被轉(zhuǎn)換的音頻文件位置
fseek(pcm,4*1024, SEEK_CUR);//skip file header
FILEFILE*mp3= fopen([mp3FilePathcStringUsingEncoding:1],"wb");//output 輸出生成的Mp3文件位置
constintPCM_SIZE =8192;
constintMP3_SIZE =8192;
shortintpcm_buffer[PCM_SIZE*2];
unsignedcharmp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_in_samplerate(lame,11025.0);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do{
read = fread(pcm_buffer,2*sizeof(shortint), PCM_SIZE, pcm);
if(read ==0)
write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
else
write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
fwrite(mp3_buffer, write,1, mp3);
}while(read !=0);
lame_close(lame);
fclose(mp3);
fclose(pcm);
}
@catch(NSException*exception) {
NSLog(@"%@",[exceptiondescription]);
}
@finally{
self.audioFileSavePath= mp3FilePath;
NSLog(@"MP3生成成功: %@",self.audioFileSavePath);
}
}
(上面的代碼都是網(wǎng)上copy的,重點看參數(shù)的設(shè)置)轉(zhuǎn)碼成功后靡羡,如果你用audioPlayer.duration獲取播放時間系洛,你會發(fā)現(xiàn)時間不準(zhǔn)
看解決方案:
//只有這個方法獲取時間是準(zhǔn)確的 audioPlayer.duration獲得的時間不準(zhǔn)
AVURLAsset* audioAsset =[AVURLAssetURLAssetWithURL:fileUrloptions:nil];
CMTime audioDuration = audioAsset.duration;
floataudioDurationSeconds =CMTimeGetSeconds(audioDuration);
用上面這個方法,你就會發(fā)現(xiàn)獲取的時間準(zhǔn)了略步,哈哈 解決問題C璩丁!L吮 U莱稀!