iOS wav转mp3以及意见简单音频录制格式
简介
基于wav音频文件太大,因项目上传作业录音,可能一次上传几十上百个wav 文件,就产生了将wav格式的录音转换成wav转换成轻量级的mp3上传的需求.
实现
实现是基于lame库的. 至于lame库的下载导入自己Google吧.
-(NSString *)changeWavToMp3WithOriginalPath:(NSString*)originalPath{
NSString * mp3Path = [[originalPath stringByDeletingLastPathComponent]stringByAppendingPathComponent:@"sentenceRecoder.mp3"];
@try {
int read, write;
FILE *pcm = fopen([originalPath cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
fseek(pcm, 4*1024, SEEK_CUR); //skip file header
FILE *mp3 = fopen([mp3Path 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_in_samplerate(lame,8000);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
lame_set_brate (lame, 128 );
lame_set_quality(lame,2);
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 {
}
[[NSFileManager defaultManager] removeItemAtPath:originalPath error:NULL];
return mp3Path;
}
一些音频格式Mark
1.aac格式 标准配置
@{AVFormatIDKey: @(kAudioFormatMPEG4AAC),
AVEncoderAudioQualityKey:@(AVAudioQualityMax),
AVSampleRateKey: @11025.0f,
AVNumberOfChannelsKey: @2,
AVLinearPCMBitDepthKey: @16};
2. wav 格式 标准配置
@{AVFormatIDKey: @(kAudioFormatLinearPCM),
AVSampleRateKey: @8000.00f,
AVNumberOfChannelsKey: @1,
AVLinearPCMBitDepthKey: @16,
AVLinearPCMIsNonInterleaved: @NO,
AVLinearPCMIsFloatKey: @NO,
AVLinearPCMIsBigEndianKey: @NO};