从应用内播放视频?

时间:2013-10-11 20:29:11

标签: ios objective-c cocoa-touch avplayer

我正在尝试使用AVPlayer从我的应用播放本地视频。我到处寻找,但找不到任何有用的教程/演示/文档。这是我正在尝试的,但它不是在玩。知道为什么吗?该URL有效,因为我使用相同的URL成功使用MPMoviePlayer播放视频。

       Video *currentVideo = [videoArray objectAtIndex:0];

    NSString *filepath = currentVideo.videoURL;
    NSURL *fileURL = [NSURL fileURLWithPath:filepath];

    AVURLAsset *asset = [AVURLAsset assetWithURL: fileURL];
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset: asset];
    self.player = [[AVPlayer alloc] initWithPlayerItem: item];


    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;


    layer.frame = CGRectMake(0, 0, 1024, 768);
    [self.view.layer addSublayer: layer];


    [self.player play];

1 个答案:

答案 0 :(得分:4)

我认为问题在于您假设执行此行AVURLAsset *asset = [AVURLAsset assetWithURL: fileURL];后资产已准备好使用。如AV Foundation Programming Guide

中所述,情况并非如此
    You create an asset from a URL using AVURLAsset. Creating the asset, however, 
    does not necessarily mean that it’s ready for use. To be used, an asset must 
    have loaded its tracks.

创建资产后,尝试加载它的轨道:

AVURLAsset *asset = [AVURLAsset URLAssetWithURL:fileURL options:nil];
NSString *tracksKey = @"tracks";

[asset loadValuesAsynchronouslyForKeys:@[tracksKey] completionHandler:
 ^{
     NSError *error;
     AVKeyValueStatus status = [asset statusOfValueForKey:tracksKey error:&error];

     if (status == AVKeyValueStatusLoaded) { 

         // At this point you know the asset is ready
         self.playerItem = [AVPlayerItem playerItemWithAsset:asset];

         ...
     }
 }];

请参阅this link查看完整示例。

希望这有帮助!