在AVCaptureMovieFileOutput之后使用AVPlayer播放视频

时间:2015-10-11 22:36:53

标签: ios avfoundation avplayer avcapturemoviefileoutput

我用AVFoundation创建了一个类似于Snapchat的自定义相机。图片方面有效:拍照并显示图片。现在我正在尝试拍摄视频并显示视频。

我已经捕获了一个成功的视频文件,经过测试并与MPMoviePlayer配合使用,但无法在AVPlayer上播放。

- (void)takeVideoAction:(id)sender {
    NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"output.mp4"];

    NSFileManager *manager = [[NSFileManager alloc] init];
    if ([manager fileExistsAtPath:outputPath]){
        [manager removeItemAtPath:outputPath error:nil];
    }
   [movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputPath] recordingDelegate:self];
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{


            AVURLAsset *asset = [AVURLAsset URLAssetWithURL:outputFileURL options:nil];
            [asset loadValuesAsynchronouslyForKeys:@[@"tracks"] completionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                 NSError *error = nil;
                 if([asset statusOfValueForKey:@"tracks" error:&error] == AVKeyValueStatusFailed){
                    NSLog(@"error: %@", [error description]);
                }
                else{
                    self.playerItem = [AVPlayerItem playerItemWithAsset:asset];
                    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
                    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
                    self.playerLayer.frame = self.view.bounds;
                    [self.view.layer addSublayer:self.playerLayer];

                    [self.player play];
                }
            });
        }];
    }

这是我第一次使用AVFoundation& AVPlayer。是否在资产加载后我不能[self.player play]?我需要等待商品状态为AVPlayerItemStatusReadyToPlay

错误:错误域= NSURLErrorDomain代码= -1100“在此服务器上找不到请求的网址。”

1 个答案:

答案 0 :(得分:1)

我正在使用AVPlayerLayer播放视频。我使用下面的代码,它工作正常。

AVPlayer *avPlayerq = [AVPlayer playerWithURL:NSURL];
avPlayerq.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayerq];
videoLayer.frame= self.view.bounds;
videoLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:videoLayer];
[avPlayerq play];

希望这可以帮助你。