AVPlayer基本使用方法

AVPlayer同样适用与本地和远程媒体文件。可以通过AVPlayerLayer来显示。

AVURLAsset *avasset;

AVPlayerItem *item;

AVPlayer *player;

AVPlayerLayer *playerLayer;

CMTime totalTime;

CGFloat totalMovieDuration;


- (void)setupPlaybackForURL:(NSURL *)url
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:url]];
    avasset = [[AVURLAsset alloc] initWithURL:url options:nil];
    //avasset = [AVURLAsset URLAssetWithURL:url options:nil];
    item = [[AVPlayerItem alloc] initWithAsset:avasset];
    //item = [AVPlayerItem playerItemWithAsset:avasset];
    
    if(player.currentItem)
        [player replaceCurrentItemWithPlayerItem:item];
    else
        player = [[AVPlayer alloc] initWithPlayerItem:item];
    //player = [AVPlayer playerWithPlayerItem:item];

    playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    
    totalTime = item.duration;
    totalMovieDuration = (CGFloat)totalTime.value/totalTime.timescale;
    
    playerLayer.frame = CGRectMake(0, 0, 100, 70);
    
    playerLayer.backgroundColor = [UIColor blackColor].CGColor;
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    //playerLayer.shadowOffset = CGSizeMake(0, 3);
    //playerLayer.shadowRadius = 5.0;
    //playerLayer.shadowColor = [UIColor blackColor].CGColor;
    //playerLayer.shadowOpacity = 0.8;
    //[uiView.layer addSublayer:playerLayer];
    
    playerLayer.hidden = NO;
    NSString *tracksKey = @"tracks";
    [avasset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:tracksKey] completionHandler:
     ^{
         dispatch_async(dispatch_get_main_queue(),
                        ^{
                            NSError *error = nil;
                            AVKeyValueStatus status = [avasset statusOfValueForKey:tracksKey error:&error];
                            
                            if (status == AVKeyValueStatusLoaded) {
                                
                                [player pause];
                            }
                            else {
                                // You should deal with the error appropriately.
                                NSLog(@"The asset's tracks were not loaded:\n%@", [error localizedDescription]);
                            }
                        });
     }];
}


判断播放暂停状态

没有专门的pause或者playing状态,可以利用rate属性:

rate的值为0.0表示暂停视频,而1.0的值是在当前项目的自然速率播放。

if(player.rate == 1.0)
{
      playingStatue = YES;
}
else
{
       playingStatue = NO;
}




你可能感兴趣的:(iOS,ios,AVPlayer)