當(dāng)我們?cè)谶M(jìn)行音頻處理的時(shí)候鲫咽,我們能夠進(jìn)行編碼成為 .caf格式,但是 .mp3 才是更方便和更為流行的格式溃斋。當(dāng)然主要原因是 .caf 5M/minute 的文件大小讓我們無可奈何界拦,擁有高壓縮率的 .mp3站出來了。
當(dāng)然梗劫,一個(gè)原因是Apple 眾多文件格式中享甸,包括MPEG-1 (.mp3), MPEG-2 ADTS (.aac), AIFF, CAF, and WAVE。最重要的事是你可以僅僅使用CAF梳侨,因?yàn)樗馨魏蝘phone支持的編碼格式的數(shù)據(jù)蛉威,在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;
}
}
}];
}
導(dǎo)出音頻文件丙躏,利用支持的 AVAssetExportPresetAppleM4A 編碼最后轉(zhuǎn)換成mp3,然并卵择示!那么問題來了,事實(shí)上在Apple 框架支持中不支持mp3的編碼晒旅,只有解碼栅盲,在蘋果官方ipod,itunes中是大力支持AAC格式編碼的敢朱,當(dāng)然為了推廣卻沒有被人們所熟悉剪菱。
最后,我們只能通過第三方的框架LameMP3Encoder去轉(zhuǎn)碼拴签,LAME是高質(zhì)量的MPEG音頻層III(MP3)編碼器孝常,mp3的流行也是LAME算法的一個(gè)功勞。使用方法如下所示:
- 導(dǎo)入libmp3lame.a靜態(tài)庫和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);
}
}