自定义视频播放器 -- AVPlayer

一直都在用系统的播放器,但发觉太局限了,很多功能都不能实现。所以就自己写了个视频播放器。

先来看看效果图:
1.可以左右滑动视频播放页面来控制进度
2.缓冲条,进度条自定义。
3.飞行模式下崩溃状态修复

自定义视频播放器 -- AVPlayer_第1张图片
视频播放中

这个应用很简单下面有进度条,缓存带,总播放时间。左右滑动视频view时,可以控制播放的时间。

ok 我们先来配置avplayer

NSString * url = @"http://ouzhenxuan.file.alimmdn.com/560a4ced60b258073cc75269/ios1444120900.jpg?t=1444120909931";
    
    NSURL *sourceMovieURL = [NSURL URLWithString:url];
    
    //使用playerItem获取视频的信息,当前播放时间,总时间等
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:sourceMovieURL];
    //player是视频播放的控制器,可以用来快进播放,暂停等
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_cusromPlayer.player];
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [_cusromPlayer setPlayer:player];
    [_cusromPlayer.player play];
    isPlaying = YES;

配置完后,我们添加 1)视频准备完毕 2)缓冲完毕 3)播放完毕的监听。

[_cusromPlayer.player.currentItem addObserver:self forKeyPath:@"status"
                                                          options:NSKeyValueObservingOptionNew
                                                          context:nil];
[_cusromPlayer.player.currentItem  addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
   
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_cusromPlayer.player.currentItem];

监听完后实现方法

#pragma mark - 处理视频加载完毕,缓冲处理,还有网络不好的情况。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *playerItem = (AVPlayerItem*)object;
        if (playerItem.status==AVPlayerStatusReadyToPlay) {
            //视频加载完成

            //计算视频总时间
            CMTime totalTime = playerItem.duration;
            totalMovieDuration = (CGFloat)totalTime.value/totalTime.timescale;
            NSDate *d = [NSDate dateWithTimeIntervalSince1970:totalMovieDuration];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            if (totalMovieDuration/3600 >= 1) {
                [formatter setDateFormat:@"HH:mm:ss"];
            }
            else
            {
                [formatter setDateFormat:@"mm:ss"];
            }
            NSString *showtimeNew = [formatter stringFromDate:d];
            self.lab.text = showtimeNew;

        }else {
            //网络不好,飞行模式的时候处理错误
            [self.cusromPlayer.player pause];
            [self.cusromPlayer.player setRate:0];
            
            [self.cusromPlayer.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
            [self.cusromPlayer.player.currentItem removeObserver:self forKeyPath:@"status" context:nil];
            [self.cusromPlayer.player replaceCurrentItemWithPlayerItem:nil];
            totalMovieDuration = 0;
            //            self.cusromPlayer.player.currentItem = nil;
            self.cusromPlayer.player = nil;
            [[NSNotificationCenter defaultCenter] removeObserver:self];
            [self.cusromPlayer.player.currentItem cancelPendingSeeks];
            [self.cusromPlayer.player.currentItem.asset cancelLoading];
            
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"网络不好" message:@"请检查网络配置" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
            [alertView show];
            
        }
    }
    if ([keyPath isEqualToString:@"loadedTimeRanges"])
    {
        float bufferTime = [self availableDuration];
        NSLog(@"缓冲进度%f",bufferTime);
        float durationTime = CMTimeGetSeconds([[_cusromPlayer.player currentItem] duration]);
        [self.progressView setProgress:bufferTime/durationTime animated:YES];
    }
    
}

如果在飞行模式下,播放视频必定崩溃,所以我们必须对准备播放失败的时候进行处理。将avplayer给注销掉,不然它会一直请求播放视频,导致崩溃。

进度条:是用了UISlider,将它左边和右边的图修改了图片以后,就会变成我们现在看到的效果了。

 UIImage *stetchLeftTrack = [[UIImage imageFromColor:[UIColor redColor] frame:CGRectMake(0, 0, 1, 12)]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    UIImage *stetchRightTrack = [[UIImage imageFromColor:[UIColor clearColor] frame:CGRectMake(0, 0, 1, 12)] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    //滑块图片
    UIImage *thumbImage = [UIImage imageFromColor:[UIColor clearColor] frame:CGRectMake(0, 0, 1, 12)];

现在的播放器可能还有其他的缺陷,如果你有好的修改方案,请在github上fork。
https://github.com/ouzhenxuan/avplayer

你可能感兴趣的:(自定义视频播放器 -- AVPlayer)