当我们在进行音频处理的时候,我们能够进行编码成为 .caf格式,但是 .mp3 才是更方便和更为流行的格式。当然主要原因是 .caf 5M/minute 的文件大小让我们无可奈何,拥有高压缩率的 .mp3站出来了。
当然,一个原因是Apple 众多文件格式中,包括MPEG-1 (.mp3), MPEG-2 ADTS (.aac), AIFF, CAF, and WAVE。最重要的事是你可以仅仅使用CAF,因为它能包含任何iphone支持的编码格式的数据,在iPhone上面它是推荐的文件格式。
功能所需,我们需要输出 .mp3 文件,OK,AVFoundation framework:
-(void)handleExportTapped :(NSURL *)assetURL
{
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc]
initWithAsset: songAsset
presetName: AVAssetExportPresetAppleM4A];
NSLog (@"created exporter. supportedFileTypes: %@", exporter.supportedFileTypes);
exporter.outputFileType = @"com.apple.m4a-audio";
NSString *exportFile = [myDocumentsDirectory() stringByAppendingPathComponent: @"exported.m4a"];
NSURL *exportURL = [NSURL fileURLWithPath:exportFile];
exporter.outputURL = exportURL;
[exporter exportAsynchronouslyWithCompletionHandler:^{
AVAssetExportSessionStatus status = [exporter status];
switch (status)
{
case AVAssetExportSessionStatusCompleted:
{
NSLog(@"export is ok");
break;
}
case AVAssetExportSessionStatusFailed:
{
break;
}
default:
{
break;
}
}
}];
}
导出音频文件,利用支持的 AVAssetExportPresetAppleM4A 编码最后转换成mp3,然并卵!那么问题来了,事实上在Apple 框架支持中不支持mp3的编码,只有解码,在苹果官方ipod,itunes中是大力支持AAC格式编码的,当然为了推广却没有被人们所熟悉。
最后,我们只能通过第三方的框架LameMP3Encoder去转码,LAME是高质量的MPEG音频层III(MP3)编码器,mp3的流行也是LAME算法的一个功劳。使用方法如下所示:
- 导入libmp3lame.a静态库和lame.h头文件
- (void)cafToMp3:(NSString*)cafFileName
{
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
_mp3FilePath = [docsDir stringByAppendingPathComponent:@"record.mp3"];
@try {
int read, write;
FILE *pcm = fopen([cafFileName cStringUsingEncoding:1], "rb");
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_t lame = lame_init();
lame_set_in_samplerate(lame, 44100);
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 {
//Detrming the size of mp3 file
NSFileManager *fileManger = [NSFileManager defaultManager];
NSData *data = [fileManger contentsAtPath:_mp3FilePath];
NSString* str = [NSString stringWithFormat:@"%d K",[data length]/1024];
NSLog(@"size of mp3=%@",str);
}
}