IOS caf音频文件如何转化成mp3文件

本文介绍了在iOS中如何使用AVAudioRecorder录制caf格式音频,并通过lame库将其转换为mp3。讨论了在转换过程中遇到的问题,如lame版本、AVFoundation框架的引用、文件路径处理以及AVAudioPlayer的播放设置等。
摘要由CSDN通过智能技术生成

IOS录制音频 我用的是AVAudioRecorder这个控件,默认录制为caf格式文件,可用第三方lame转成mp3格式文件

使用前先引用框架 <AVFoundation/AVFoundation.h>

1.录音用的控件是AVAudioRecorder,录音的主要代码:

recordedFile=[NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"%@.%@", @"aaa",@"caf"]]];//录音文件的位置
recorder = [[AVAudioRecorder alloc] initWithURL:recordedFile settings:recordSetting error:nil];
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    [recorder record];    

2.录音完成后,引用了lame之后,转化的过程核心代码:

    NSString *cafFilePath =[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.
ios录音的caf文件MP3文件,以兼容android 注意音频参数的设置,如果声音异常,请调整参数。 code: AVAudioSession *session = [AVAudioSession sharedInstance]; NSError *sessionError; [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError]; _sampleRate = 11025;//8000;//44100; _quality = AVAudioQualityLow; if(session == nil) NSLog(@"Error creating session: %@", [sessionError description]); else [session setActive:YES error:nil]; NSString *cafFilePath = strCaf; // NSString *mp3FileName = @"Mp3File"; // mp3FileName = [mp3FileName stringByAppendingString:@".mp3"]; NSString *mp3FilePath = strMP3Path;//[[NSHomeDirectory() stringByAppendingFormat:@"/Documents/"] stringByAppendingPathComponent:mp3FileName]; @try { int read, write; FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb"); //source fseek(pcm, 4*1024, SEEK_CUR); //skip file header FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output 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, _sampleRate); 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 { }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值