需要引入lame静态库
#import "lame.h"
- (void)convertPCMToMp3Success:(void(^)(NSString *mp3Path))success
failure:(void(^)(NSError *error))failure {
NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/mp3.mp3"];
NSString *mp3FilePath = filePath;
NSString *LicensePath = [NSString pathWithComponents:@[[[NSBundle mainBundle] bundlePath], @"temp.pcm"]];
NSString *pcmFilePath = LicensePath;
@try {
int read,write;
// 只读方式打开被转换音频文件
FILE *pcm = fopen([pcmFilePath cStringUsingEncoding:1], "rb");
if (!pcm) {
return;
}
// 删除头,否则在前一秒钟会有杂音
fseek(pcm, 4 * 1024, SEEK_CUR);
// 只写方式打开生成的MP3文件
FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");
const int PCM_SIZE = 8192;
const int MP3_SIZE = 8192;
short int pcm_buffer[PCM_SIZE * 2];
unsigned char mp3_buffer[MP3_SIZE];
// 这里要注意,lame的配置要跟AVAudioRecorder的配置一致,否则会造成转换不成功
lame_t lame = lame_init();
// 采样率需要和百度语音一致(百度16k,mp3一般是双声道的,设置8k)
lame_set_in_samplerate(lame, 8000.0);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do {
//以二进制形式读取文件中的数据
read = (int)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);
}
/*
* 二进制形式写数据到文件中
*
* mp3_buffer:数据输出到文件的缓冲区首地址
* write:一个数据块的字节数
* 1:指定一次输出数据块的个数
* mp3:文件指针
*/
fwrite(mp3_buffer, write, 1, mp3);
} while (read != 0);
lame_close(lame);
fclose(mp3);
fclose(pcm);
} @catch (NSException *exception) {
if (failure) {
failure(nil);
}
} @finally {
if (success) {
success(mp3FilePath);
}
}
}
lame静态库下载地址
链接: https://pan.baidu.com/s/1BLw5kbmrpXP1RaV5PEuqSg 密码: jnmk