2016-02-03 48 views
1

我使用AVFoundation錄製視頻,錄製完成後視頻會自動運行。 這是碼記錄視頻:使用AVFoundation錄製後無法播放視頻

- (IBAction)captureVideo:(id)sender { 
if (!isRecording) { 
    isRecording = YES; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"dd-MM-yyyy||HH:mm:SS"]; 
    NSDate *now = [[NSDate alloc] init]; 
    NSString *theDate = [dateFormat stringFromDate:now]; 

    NSString *videoPath = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%@/%@.mov",documentsDirectory,theDate]]; 
    outputURL = [NSURL fileURLWithPath:videoPath]; 
    [movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self]; 
} else{ 
    isRecording = NO; 
    [movieFileOutput stopRecording]; 

    [self playVideo]; 
} 
} 

播放視頻:

AVPlayer *player = [AVPlayer playerWithURL:outputURL]; 
AVPlayerViewController *playerViewController = [AVPlayerViewController new]; 
playerViewController.player = player; 

playerViewController.view.frame = CGRectMake(0, 150, self.view.frame.size.width, 400); 
[self.view addSubview:playerViewController.view]; 
[player play]; 

奇怪的是,我不能記錄後播放視頻,但是當我把一個斷點線AVPlayer *player = [AVPlayer playerWithURL:outputURL];。當程序遇到這個斷點時,我繼續運行它。它運行良好。 我不知道爲什麼。 任何幫助或建議,將不勝感激。謝謝。

+0

我想你應該記錄到緩衝區/高速緩存或其他臨時位置,而不是正確的文件時被存儲。它會讓你的視頻有機會獲得記錄,任何操作系統或處理框架都有機會在保存到文件之前完成其工作。斷點指向它停止的那個方向,它給它一個寫完文件的機會。 – noobsmcgoobs

+0

查看此鏈接https://www.objc.io/issues/23-video/capturing-video/特別是有關'AVCaptureDataOutput'和'AVAssetWriter'的章節 – noobsmcgoobs

回答

0

看着Apple's documentation for the stopRecording method in AVCaptureFileOutput,我們可以看到有一個名爲captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:的AVCaptureFileOutputRecordingDelegate方法。

所以它看起來像你試圖播放視頻時,它沒有寫入磁盤。磁盤寫入是異步完成的,因此當下一行([player play])正在執行時,視頻肯定不會寫入。

我不知道你在哪裏初始化了你的對象,但你應該設置它的委託(它可以是視圖控制器)。

完成後,只需實施captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:方法(無論如何都需要),並且您可以將[player play]方法放在那裏播放視頻(在驗證沒有發生錯誤之後)。

下面是一個示例實現的方法:

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error { 

    if ([error code] == noErr) { 
     [player play]; 
    } else { 
     //Let the user know something went wrong 
     NSLog(@"Error recording to output file: %@",error.localizedDescription); 
    } 

} 
0

我固定我的問題。 停止記錄後,不要致電[self playVideo];。我把它放在AVCaptureMovieFileOutput的委託

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{ 
    if ([error code] == noErr) { 
     [self playVideo]; 
    } 
}