2011-07-02 146 views
0
// 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按鈕,我得到的結果如下:無法重新啓動AVAudioRecorder

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 

有什麼建議嗎?

+0

我沒有發佈這個答案,因爲我不確定它對我來說甚至是有意義的:/但是,它可能與運行時環境有關嗎?僅僅因爲你打電話給記錄器開始和停止並不意味着它實際上是在那時開始或停止。主運行時線程控制執行。 (據我所知,AV方法也在自己的線程中運行,如果是的話,也許你會遇到競爭狀態)。您可能需要實現AVAudiRecorderDelegate,以便在再次重新啓動之前驗證錄製是否先停下來。 – carbonbasednerd

+0

@cabonbasednerd謝謝。你的回答就是發生了什麼。 – aXqd

回答

0

您可能需要使用暫停方法而不是停止。如果您參考AVAudioRecorder的方法文檔停止將關閉音頻文件,這似乎會導致在下次啓動文件時覆蓋該文件。

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,它創建(或擦除)的音頻文件,並準備系統用於記錄。