iOS-PCM文件转MP3文件

PCM音频文件转MP3音频文件,也可以是直接NSData转换。

导入Lame库

Lame库是一个开源的编码转换库,先下载Lame后,导入到项目中,并导入以下两个Framework:

AVFoundation、AudioToolbox

编码转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#import "lame.h"

- (void)decode{
NSData *totalData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"numb" ofType:@"pcm"]];
int frame = 1048576 / 4;
for(int i = 0; i < totalData.length; i += frame){
int size = MIN(frame, (int)totalData.length - i);
[self pcmToMp3:[totalData subdataWithRange:NSMakeRange(i, size)]];
}
NSLog(@"End..");
}

- (NSData*)pcmToMp3:(NSData*)pcmData
{
int PCM_SIZE = (int)pcmData.length;
int MP3_SIZE = (int)pcmData.length;
short int *pcm_buffer = (short int*)pcmData.bytes;
unsigned char mp3_buffer[MP3_SIZE];


lame_t lame = lame_init();
lame_set_in_samplerate(lame, 采样率);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
NSMutableData *mp3Data = [NSMutableData new];
int result = lame_encode_buffer_interleaved(lame, pcm_buffer, PCM_SIZE, mp3_buffer, MP3_SIZE);
lame_close(lame);
if(result > 0){
NSLog(@"PCM encode success:%d..", result);
[mp3Data appendBytes:mp3_buffer length:result];
}else{
NSLog(@"PCM encode fail:%d..", result);
}

return mp3Data;
}

注意,修改一下采样率,每首歌的采样率不同。