iOS--AVAudioRecorder如何录制MP3

AVAudioRecorder简介

录音机,提供了在应用程序中的音频记录能力。作为与 AVAudioPlayer 相对应的 API,AVAudioRecorder 是将音频录制为文件的最简单的方法。除了用一个音量计接受音量的峰值和平均值以外,这个 API 简单粗暴,如果你的使用场景很简单的话,这可能恰恰就是你想要的方法。

录音配置

创建AVAudioSession

想要录音首先要创建一个AVAudioSession,这个通道用来调用录音设备;


    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    NSError *sessionError;
    
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    if(session == nil){
        
        NSLog(@"Error creating session: %@", [sessionError description]);
        
    }
    else{
        
        [session setActive:YES error:nil];
        
    }

        

创建录音设置字典

想要录音 总得配置点啥吧

    NSMutableDictionary *audioSetting = [NSMutableDictionary dictionary]; 
    
    // 设置录音格式 kAudioFormatMPEGLayer3设置貌似是没用的 默认设置就行
    //[audioSetting setObject:@(kAudioFormatMPEGLayer3) forKey:AVFormatIDKey];
    
    // 设置录音采样率,8000 44100 96000,对于一般录音已经够了
    [audioSetting setObject:@(22150) forKey:AVSampleRateKey];
    
    // 设置通道 1 2
    [audioSetting setObject:@(1) forKey:AVNumberOfChannelsKey];
    
    // 每个采样点位数,分为8、16、24、32
    [audioSetting setObject:@(16) forKey:AVLinearPCMBitDepthKey];
    
    // 是否使用浮点数采样 如果不是MP3需要用Lame转码为mp3的一定记得设置NO!(不然转码之后的声音一直都是杂音)
    // 是否使用浮点数采样 如果不是MP3需要用Lame转码为mp3的一定记得设置NO!(不然转码之后的声音一直都是杂音)
    // 是否使用浮点数采样 如果不是MP3需要用Lame转码为mp3的一定记得设置NO!(不然转码之后的声音一直都是杂音)
    
    [audioSetting setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    
    // 录音质量
    [audioSetting setObject:@(AVAudioQualityHigh) forKey:AVEncoderAudioQualityKey];
    

创建一个录音文件的存放路径

录完音总得给个地方存吧

    //  在Documents目录下创建一个名为FileData的文件夹
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"Cache/AudioData"];
    NSLog(@"%@",path);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"创建文件夹失败!");
        }
        NSLog(@"创建文件夹成功,文件路径%@",path);
    }
    
     //每次启动后都保存一个新的文件中
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    
    [formatter setDateFormat:@"yyyy_MM_dd_HH_mm_ss"];
   
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    
    // 想要录制MP3格式的 这里 MP3 必须大写 !!!!(苹果的所有后缀名都是大写,所以这是个坑)
    // 想要录制MP3格式的 这里 MP3 必须大写 !!!!(苹果的所有后缀名都是大写,所以这是个坑)
    // 想要录制MP3格式的 这里 MP3 必须大写 !!!!(苹果的所有后缀名都是大写,所以这是个坑)
    
    path = [path stringByAppendingFormat:@"/%@.MP3",dateStr];
    
    NSLog(@"file path:%@",path);
    
    NSURL *url=[NSURL fileURLWithPath:path];
    

录音完整操作

    //如果是在录音就不做动作
    if ([self.audioRecorder isRecording]) {
        return;
    }
    
    //创建录音通道
    [self setAudioSession];
    
    //创建录音格式设置
    NSDictionary *setting = [self getAudioSetting];
    
    //创建录音文件保存路径
    NSURL *url = [self getSavePath];
    
    //创建录音机
    NSError *error=nil;
    self.audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
    self.audioRecorder.delegate=self;
    self.audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
    
    if (error) {
        NSLog(@"创建录音机时发生错误,信息:%@",error.localizedDescription);
    }
    else{
        if (![self.audioRecorder isRecording]) {
            
            NSLog(@"录音开始");
            
            [self.audioRecorder record];
            
        }
    }

相关链接

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
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 { }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卟败灬筱龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值