背景:网上好多都没说到解决音频获取时长的要点,索性自己再总结一下。
1.需求:项目中服务器需要上传mp3格式的音频文件,所以本地需要先把.caf格式转为mp3格式上传。
2.问题:从服务器返回的音频url地址获取音频时长不准,且每次可能不一样。
3.分析可能有原因:
1.音频转为mp3时参数设置问题,如采样通道数、采样率等。
2.[AVURLAsset URLAssetWithURL:[NSURL URLWithString:url] options:nil];中option参数没有设置,网上大多这里都是设为nil。
4.测试正常的音频录音参数
- (NSDictionary *)recordingSettings
{
NSMutableDictionary *recordSetting =[NSMutableDictionary dictionaryWithCapacity:10];
[recordSetting setObject:[NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey];
//2 采样率
[recordSetting setObject:[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];
//3 通道的数目
[recordSetting setObject:[NSNumber numberWithInt:2]forKey:AVNumberOfChannelsKey];
//4 采样位数 默认 16
[recordSetting setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//5音频质量,采样质量
[recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
return recordSetting;
}
5.测试正常的音频mp3转换方式
//CAF转换mp3的lame方法
+ (NSString *)audioCAFtoMP3:(NSString *)wavPath {
NSString *cafFilePath = wavPath;
NSString *mp3FilePath = [NSString stringWithFormat:@"%@.mp3",[NSString stringWithFormat:@"%@%@",[cafFilePath substringToIndex:cafFilePath.length - 4],[self getTimestamp]]];
@try {
int read, write;
FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
fseek(pcm, 4*1024, SEEK_CUR); //skip file header
FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置
const int PCM_SIZE = 8192;
const int MP3_SIZE = 8192;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_num_channels(lame,2);//通道数跟原音频参数设置一致
lame_set_in_samplerate(lame, 11025.0);//采样率跟原音频参数设置一致
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do {
read = fread(pcm_buffer, 2*sizeof(short int), 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(@"%@",[exception description]);
}
@finally {
[YWCommonUtils deleteFileWithPath:cafFilePath];
return mp3FilePath;
}
}
6.测试正常的音频时间长度设置
+ (NSTimeInterval)AudioDurationFromUrl:(NSString *)url {
//只有这个方法获取时间是准确的 audioPlayer.duration获得的时间不准
AVURLAsset* audioAsset = nil;
NSDictionary *dic = @{AVURLAssetPreferPreciseDurationAndTimingKey:@(YES)};
if ([url hasPrefix:@"http://"]) {
audioAsset =[AVURLAsset URLAssetWithURL:[NSURL URLWithString:url] options:dic];
}else {//播放本机录制的文件
audioAsset =[AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:url] options:dic];
}
CMTime audioDuration = audioAsset.duration;
float audioDurationSeconds =CMTimeGetSeconds(audioDuration);
return audioDurationSeconds;
}