2013-10-11 38 views
3

我想从我的应用程序使用AVPlayer播放本地视频。我已到处寻找,但找不到任何有用的教程/演示/文档。这是我正在尝试的,但它不是在玩。任何想法为什么?该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

我相信问题是,你假设执行该行后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看到完整的例子。

希望这会有所帮助!

+0

非常感谢!对不起,延迟接受! –

+0

@LuisCien我现在面临同样的问题,我已经使用你的代码。但它返回了我'AVKeyValueStatusFailed',请看我的问题,并建议我一些,如果你明白。 http://stackoverflow.com/questions/29255776/cannot-get-the-duration-of-mp4-file-by-using-avasset-or-avurlasset –