最近在项目中用到lame转码将wav转换成MP3格式,其中遇到了不少的坑,最大的一个就是转码完成后, 用audioPlayer.duration获取的时间不准,而且获取的时间一直在变,最后在一位大神的帮助下解决了这个问题,下面就分享下解决过程(把整个转码过程都说一遍)!
我从录制开始讲:
首先在录音时要设置录音参数记住了,通道数目必须设置为2,否则转码后声音不对
//录音设置
NSMutableDictionary*recordSettings = [[NSMutableDictionaryalloc]init];
//录音格式 无法使用
[recordSettings setValue :[NSNumbernumberWithInt:kAudioFormatLinearPCM]forKey:AVFormatIDKey];
//采样率
[recordSettings setValue :[NSNumbernumberWithFloat:11025.0]forKey:AVSampleRateKey];//44100.0
//通道数
[recordSettings setValue :[NSNumbernumberWithInt:2]forKey:AVNumberOfChannelsKey];
//线性采样位数
//[recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
//音频质量,采样质量
[recordSettingssetValue:[NSNumbernumberWithInt:AVAudioQualityMin]forKey:AVEncoderAudioQualityKey];
接着是转码了注意:注意了:录音的采样率和转码的采样率必须一样 必须一样
- (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 被转换的音频文件位置
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);
}
}
(上面的代码都是网上copy的,重点看参数的设置)转码成功后,如果你用audioPlayer.duration获取播放时间,你会发现时间不准
看解决方案:
//只有这个方法获取时间是准确的 audioPlayer.duration获得的时间不准
AVURLAsset* audioAsset =[AVURLAssetURLAssetWithURL:fileUrloptions:nil];
CMTime audioDuration = audioAsset.duration;
floataudioDurationSeconds =CMTimeGetSeconds(audioDuration);
用上面这个方法,你就会发现获取的时间准了,哈哈 解决问题!!!!!