4

我正在尝试使用 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];
4

1 回答 1

5

我认为问题在于您假设在执行此行后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];

         ...
     }
 }];

请参阅此链接以查看完整示例。

希望这可以帮助!

于 2013-10-11T21:01:55.537 回答