// ps:需要添加libmp3lame.a靜態庫,引入lame.h,真機需關閉bitcode,百度文件地址: http://pan.baidu.com/s/1mhHrqeG 密碼: bz8a
- (void)audio_PCMtoMP3
{
// self.audioFileSavePath
// NSString *mp3FileName = [_recordUrl lastPathComponent];
// NSLog(@"%@",[_recordUrl lastPathComponent]);
// mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
NSString *mp3FilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"record.mp3"];
// _recordUrl = [NSTemporaryDirectory() stringByAppendingString:@"record.caf"]; _recordUrl是音頻存儲路徑
@try {
int read, write;
FILE *pcm = fopen([_recordUrl 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_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 {
_recordUrl = mp3FilePath;
NSLog(@"MP3生成成功: %@",_recordUrl);
self.voiceData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:_recordUrl]];
[[NSFileManager defaultManager] removeItemAtURL:[NSURL fileURLWithPath:_recordUrl] error:nil]; // 生成文件移除原文件
}
}
隨筆隨記,以免忘記