Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

ios - Playing video from within app?

I am trying to play a local video from my app using AVPlayer. I have looked everywhere but can't find any useful tutorials/demos/documentation. Here is what I am trying, but it is not playing. Any idea why? The URL is valid because I was using the same one to play a video using MPMoviePlayer successfully.

       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];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe the problem is that you're assuming that after executing this line AVURLAsset *asset = [AVURLAsset assetWithURL: fileURL]; the asset is ready to use. This is not the case as noted in the 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.

After creating the asset try loading it's 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];

         ...
     }
 }];

Please refer to this link to see the complete example.

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...