ios - 关于AVAudioRecorder录音失败的问题

 海and云 发布于 2022-11-03 00:34
- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    NSString *docPath=[dirPath objectAtIndex:0];
    NSString *filePath=[docPath stringByAppendingPathComponent:@"test1.wav"];
    _url=[NSURL URLWithString:filePath];

    NSDictionary *recordSettings=[NSDictionary dictionaryWithObjectsAndKeys:
          [NSNumber numberWithInt:AVAudioQualityMin],
          AVEncoderAudioQualityKey,
          [NSNumber numberWithInt:16],
          AVEncoderBitRateKey,
          [NSNumber numberWithInt:2],
          AVNumberOfChannelsKey,
          [NSNumber numberWithFloat:44100.0],
          AVSampleRateKey,
          nil];
    NSError *error;
    //AVAudioRecorder *recorder;
    //AVAudioPlayer *player;

    _player=[[AVAudioPlayer alloc] initWithContentsOfURL:_url error:&error];
    _recorder=[[AVAudioRecorder alloc] initWithURL:_url settings:recordSettings error:nil];
    if (error) {
        NSLog(@"%@",[error localizedDescription]);
    }else{
        [_recorder prepareToRecord];
    }
}

调试的时候显示_player的值为nil,还有报错: The operation couldn’t be completed. (OSStatus error 2003334207.)我没在网上找到答案。

2 个回答
  • 楼主,解决了嘛?我也遇到同样问题,估计是转wav格式出错了

    2022-11-05 08:28 回答
  • _player的值为nil,这个应该是Xcode的BUG导致的,你如果用NSLog输出,_player应该是有值的。

    1. 记得给AVAudioRecorder设置代理
    2. iOS7及以上版本,增加了对录音功能的权限控制。你需要先判断应用程序有没有录音权限,如果应用程序不具备录音权限,提示用户打开。
      ,判断方法:
    objectivec/// 新增API,获取录音权限. 返回值,YES为无拒绝,NO为拒绝录音.
    + (BOOL)canRecord
    {
        __block BOOL bCanRecord = YES;
        if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
            AVAudioSession *audioSession = [AVAudioSession sharedInstance];
            if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
                [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                    if (granted) {
                        bCanRecord = YES;
                    } else {
                        bCanRecord = NO;
                    }
                }];
            }
        }
        return bCanRecord;
    }
    
    1. 以下代码让设备开启录音模式:
    objectivecAVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession setActive:YES error:nil];
    
    2022-11-05 08:35 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有