AVAudioRecorder不会在设备上录制

Dyl*_*o42 6 iphone avfoundation avaudiorecorder

这是我的方法:

-(void) playOrRecord:(UIButton *)sender {
    if (playBool == YES) {
        NSError *error = nil;
        NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat: @"%d", [sender tag]] ofType:@"caf"];
        NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
        AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
        [player setNumberOfLoops:0];
        [player play];      
    }
    else if (playBool == NO) {
        if ([recorder isRecording]) {
            [recorder stop];
            [nowRecording setImage:[UIImage imageNamed:@"NormalNormal.png"] forState:UIControlStateNormal];
            [nowRecording setImage:[UIImage imageNamed:@"NormalSelected.png"] forState:UIControlStateSelected];
        }
        if (nowRecording == sender) {
        nowRecording = nil;
        return;
        }
        nowRecording = sender;
        NSError *error = nil;
        NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat: @"%d", [sender tag]] ofType:@"caf"];
        NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
        [sender setImage:[UIImage imageNamed:@"RecordingNormal.png"] forState:UIControlStateNormal];
        [sender setImage:[UIImage imageNamed:@"RecordingSelected.png"] forState:UIControlStateSelected];        
        recorder = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:recordSettings error:&error];
        [recorder record];
    }
}
Run Code Online (Sandbox Code Playgroud)

大多数是自我解释; playBool是一个BOOL,当它处于播放模式时为YES.一切都在模拟器中工作,但是当我在设备上运行时,[记录器记录]返回NO.有没有人知道为什么会这样?

Mar*_*ius 17

如果代码中的任何位置都有此设置:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
Run Code Online (Sandbox Code Playgroud)

将其更改为:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
Run Code Online (Sandbox Code Playgroud)

设置错误的AVAudioSession类别将导致记录/播放失败.


Dyl*_*o42 3

好的,解决了我自己的问题;我不知道为什么,但在设备上时我必须记录到 NSTemporaryDirectory。改变它完全解决了它。