最近在項(xiàng)目中用到lame轉(zhuǎn)碼將wav轉(zhuǎn)換成MP3格式,其中遇到了不少的坑,最大的一個(gè)就是轉(zhuǎn)碼完成后, 用audioPlayer.duration獲取的時(shí)間不準(zhǔn),而且獲取的時(shí)間一直在變,最后在一位大神的幫助下解決了這個(gè)問(wèn)題,下面就分享下解決過(guò)程(把整個(gè)轉(zhuǎn)碼過(guò)程都說(shuō)一遍)!
我從錄制開(kāi)始講:
首先在錄音時(shí)要設(shè)置錄音參數(shù)記住了,通道數(shù)目必須設(shè)置為2,否則轉(zhuǎn)碼后聲音不對(duì)
//錄音設(shè)置
NSMutableDictionary*recordSettings = [[NSMutableDictionaryalloc]init];
//錄音格式 無(wú)法使用
[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的,重點(diǎn)看參數(shù)的設(shè)置)轉(zhuǎn)碼成功后,如果你用audioPlayer.duration獲取播放時(shí)間,你會(huì)發(fā)現(xiàn)時(shí)間不準(zhǔn)
看解決方案:
//只有這個(gè)方法獲取時(shí)間是準(zhǔn)確的 audioPlayer.duration獲得的時(shí)間不準(zhǔn)
AVURLAsset* audioAsset =[AVURLAssetURLAssetWithURL:fileUrloptions:nil];
CMTime audioDuration = audioAsset.duration;
floataudioDurationSeconds =CMTimeGetSeconds(audioDuration);
用上面這個(gè)方法,你就會(huì)發(fā)現(xiàn)獲取的時(shí)間準(zhǔn)了,哈哈 解決問(wèn)題?。。。?!