2013-10-11 99 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 –