簡(jiǎn)介
??? 基于wav音頻文件太大,因項(xiàng)目上傳作業(yè)錄音,可能一次上傳幾十上百個(gè)wav 文件,就產(chǎn)生了將wav格式的錄音轉(zhuǎn)換成wav轉(zhuǎn)換成輕量級(jí)的mp3上傳的需求.
?實(shí)現(xiàn)
???? 實(shí)現(xiàn)是基于lame庫的. 至于lame庫的下載導(dǎo)入自己Google吧.
-(NSString *)changeWavToMp3WithOriginalPath:(NSString*)originalPath{
???????????? NSString * mp3Path = [[originalPath stringByDeletingLastPathComponent]stringByAppendingPathComponent:@"sentenceRecoder.mp3"];
????????? @try {
????????????? int read, write;
????????????? FILE *pcm = fopen([originalPath cStringUsingEncoding:1], "rb");? //source 被轉(zhuǎn)換的音頻文件位置
???????????? 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格式 標(biāo)準(zhǔn)配置
@{AVFormatIDKey: @(kAudioFormatMPEG4AAC),
AVEncoderAudioQualityKey:@(AVAudioQualityMax),
AVSampleRateKey: @11025.0f,
AVNumberOfChannelsKey: @2,
AVLinearPCMBitDepthKey: @16};
2. wav 格式 標(biāo)準(zhǔn)配置
@{AVFormatIDKey: @(kAudioFormatLinearPCM),
AVSampleRateKey: @8000.00f,
AVNumberOfChannelsKey: @1,
AVLinearPCMBitDepthKey: @16,
AVLinearPCMIsNonInterleaved: @NO,
AVLinearPCMIsFloatKey: @NO,
AVLinearPCMIsBigEndianKey: @NO};