【问题标题】:Playing video from within app?从应用程序内播放视频?
【发布时间】:2013-10-11 20:29:10
【问题描述】:

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

【问题讨论】:

    标签: ios objective-c cocoa-touch avplayer


    【解决方案1】:

    我认为问题在于您假设在执行此行 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查看完整示例。

    希望这会有所帮助!

    【讨论】:

    • @LuisCien 我现在面临同样的问题,我已经使用了你的代码。但它返回了我AVKeyValueStatusFailed,如果您理解,请查看我的问题并建议我一些。 stackoverflow.com/questions/29255776/…
    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多