Search code examples
iphoneobjective-ciosavaudiorecorder

Failed to restart AVAudioRecorder


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];

    self.recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:@"record.caf"]] settings:nil error:nil];
}

- (void)restartBtnPushed {  
    NSLog(@"Before stop: %d", self.recorder.recording);
    [self.recorder stop];
    NSLog(@"After stop: %d", self.recorder.recording);

    [self.recorder record];
    NSLog(@"After start: %d", self.recorder.recording);
}

If I keep hitting that RESTART button, I get results as below:

Before stop: 0
After stop:  0
After start: 1
--------------------
Before stop: 1
After stop:  0
After start: 1  <-----
-------------------- |
Before stop: 0  <----|----This is wrong version
After stop:  0
After start: 1  <-----
-------------------- |
Before stop: 1  <----|----This is correct version
After stop:  0
After start: 1

I can summarize it as below:

Stopped Recorder + 'stop' + 'start' -> Recorder is running successfully
Running Recorder + 'stop' + 'start' -> Recorder fails to run

Any ideas?


Solution

  • You likely need to use the pause method rather than stop. If you refer to the method documentation for AVAudioRecorder stop will close the audio file, which seems to cause issues of overwriting the file the next time you want to start it.

    https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVAudioRecorder_ClassReference/Reference/Reference.html#//apple_ref/occ/instm/AVAudioRecorder/stop

    https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVAudioRecorder_ClassReference/Reference/Reference.html#//apple_ref/occ/instm/AVAudioRecorder/record

    Calling this method implicitly calls prepareToRecord, which creates (or erases) an audio file and prepares the system for recording.