赞
踩
在我们之前的项目,视频的播放都是使用MPMoviePlayerViewController(包含了播放的UI,并封装好了播放的一些函数),但是苹果的官网表示从IOS9版本开始,MPMoviePlayerViewController被弃用了,推荐使用AVPictureInPictureController或者AVPlayerViewController。
但是一直使用苹果封装的ViewController可控性依旧比较差,如:
(1)播放状态无法获得;
(2)置于后台和唤醒时,在不同设备上视频播放展现状态不同;
(3)视频播放进度与画面不同步;
(4)播放的声音和画面不同步;
(5)无法直接加其他UI,如:分享按钮等。
基于以上几点考虑,我决定直接用AVPlayer直接实现一个播放器,完成一些简单的播放功能。
基本功能:
(1)进度条、视频播放画面、播放时间同步;
(2)可以播放和暂停,且两种状态有不同UI切换;
(3)进度条可以拖动,且视频播放画面同步;
(4)点击关闭按钮可以销毁播放器;
(5)增加了AutoLayout布局约束
(6)视频的横竖屏切换播放与设备的横竖屏切换同步。
(7)一些小细节,如:进度条拖拽、点击、抬起时,播放/暂停按钮UI的变化;置于后台和唤醒,重新设置视频播放状态等。
代码如下:
头文件:ViewController.h
#import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> @interface ViewController : UIViewController @property (nonatomic,strong)AVPlayer *avPlayer; @property (nonatomic,strong)AVPlayerItem *avPlayerItem; @property (nonatomic,strong)AVPlayerLayer *avPlayerLayer; //装载视频layer、进度条、时间、时长等UI的容器 @property (nonatomic,strong)UIView *videoContainer; //进度条UI @property (nonatomic,strong)UISlider *progress; //当前播放时间UI @property (nonatomic,strong) UILabel *startLabel; //视频总时长UI @property (nonatomic,strong) UILabel *endLabel; //关闭按钮 @property (nonatomic,strong) UIButton *closeButton; //控制播放和暂停的按钮 @property (nonatomic,strong) UIButton *playButton; //当前播放时间 @property (nonatomic,assign) float playheadTime; //是否处于播放状态 @property (nonatomic,assign) BOOL isPlaying; //播放帧的监视器 @property (nonatomic,strong) id playTimeObserver; @end
实现:ViewController.m
<span style="font-size:14px;">#import "ViewController.h" @interface ViewController () @end static NSBundle *playerBundle; NSString * const XAdVideoStatusKey = @"status"; @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *urlString = @"要播放的视频地址 http://...."; [self configPlayerControllerWithURL:urlString]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } #pragma mark - public - (void) configPlayerControllerWithURL:(NSString *)urlString{ [self initBundle]; [self setProgressRefProperties]; [self showUI]; NSURL *url = [NSURL URLWithString:urlString]; [self setupPlayerWithURL:url]; } /* * 重头播放 */ - (void)play{ if (self.avPlayer) { self.isPlaying = YES; [self.avPlayer play]; } } /* * 暂停 */ - (void)pause { if (self.avPlayer) { [self.avPlayer pause]; self.isPlaying = NO; } } /* * 销毁对象 */ - (void)cancel { if (self.avPlayer) { [self.avPlayer pause]; } [self removeUIView]; [self removePlayerItemObserver]; [self removePlayerObserver]; [self destroyAllProperties]; } /* * 从某一帧播放 */ - (void)playFromTime:(double)time { NSLog(@"playFromTime = %f",time); if (self.avPlayer) { [self seekToTime:time]; [self.avPlayer play]; self.isPlaying = YES; } } /* * 在某一帧暂停 */ - (void)pauseOnTime:(double)time { NSLog(@"pauseOnTime = %f",time); if (self.avPlayer) { [self seekToTime:time]; [self.avPlayer pause]; self.isPlaying = NO; } } #pragma mark - action event
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。