无法重新启动AVAudioRecorder

时间:2011-07-02 09:39:10

标签: iphone objective-c ios 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);
}

如果我继续按下RESTART按钮,我会得到如下结果:

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

我可以总结如下:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可能需要使用暂停方法而不是停止。如果您参考AVAudioRecorder的方法文档,stop将关闭音频文件,这似乎会在下次启动时导致覆盖文件的问题。

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

  

调用此方法会隐式调用prepareToRecord,它会创建(或删除)音频文件并准备系统进行录制。