IOS AVAudioRecorder 录制音频

本文介绍了解决AVAudioRecorder在iOS真机上无法录音的问题,并提供了解决方案,同时分享了如何调整音频设置来改善录音质量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AVAudioRecorder 在真机上录制不了声音,但在模拟器上是可以录音的。

解决办法:

    AVAudioSession *session = [AVAudioSession sharedInstance];

    NSError *setCategoryError = nil;

    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];

在初始化AVAudioRecorder时加一下。


然后播放的时候声音很小。

解决办法:

    AVAudioSession *session = [AVAudioSession sharedInstance];

    NSError *setCategoryError = nil;

    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];


在播放前加一下。



- (void)initRecorder {
    //录音设置
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)
    [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
    //录音通道数  1 或 2
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
    NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/test.aac", strUrl]];

    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *setCategoryError = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];
    
    if(setCategoryError){
        NSLog(@"%@", [setCategoryError description]);
    }
    
    NSError *error;
    //初始化
    recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
    //开启音量检测
    recorder.meteringEnabled = YES;
    recorder.delegate = self;
}


- (void)startRecorder {
    if (recorder == nil) {
        [self initRecorder];
    }
    //创建录音文件,准备录音
    if ([recorder prepareToRecord]) {
        //开始
        [recorder record];
    }
}

- (void)pauseRecorder {
    [recorder pause];
    [timer invalidate];
}

- (void)stopRecorder {
    [recorder stop];
    [timer invalidate];
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值