Swift AVPlayer的使用

AVPlayer存在于AVFoundation中,它更加接近于底层,可以进行自定义,所以也更加灵活。AVPlayer本身并不能显示视频,而且它也不像MPMoviePlayerController有一个view属性。如果AVPlayer要显示必须创建一个播放器层AVPlayerLayer用于展示,播放器层继承于CALayer,有了AVPlayerLayer之添加到控制器视图的layer中即可。
最近实现一个基本的AVPlayer播放器,代码如下:

自定义一个View,播放器的UI部分主要在这里实现

<pre>import UIKit
import AVFoundation

protocol WXPlayerViewDelegate: NSObjectProtocol {

func wxplayer(playerView: WXPlayerView,slider: UISlider)
func wxplayer(playerView:WXPlayerView,playAndPause playBtn:UIButton)

}

class WXPlayerView: UIView {

var playerLayer: AVPlayerLayer!
var timeLabel: UILabel!
var slider: UISlider!
var progressView:UIProgressView!
var playBtn:UIButton!
var sliding = false
var playing = true
weak var delegate: WXPlayerViewDelegate?
init(){

    super.init(frame: CGRect.zero)
    self.initView()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func initView()
{
    self.playerLayer = AVPlayerLayer()
    self.layer.addSublayer( self.playerLayer)
    
    self.timeLabel = UILabel()

// self.timeLabel.backgroundColor = UIColor.red
self.timeLabel.textColor = UIColor.white
self.timeLabel.font = UIFont.systemFont(ofSize: 14)
self.addSubview(self.timeLabel)

    self.slider = UISlider()
    self.addSubview(self.slider)
    
    self.slider.minimumValue = 0
    self.slider.maximumValue = 1
    self.slider.value = 0
    self.slider.maximumTrackTintColor = UIColor.clear
    self.slider.minimumTrackTintColor = UIColor.white
    self.slider.setThumbImage(UIImage(named:"ic_shipinjindu_nor"), for: .normal)
    
    // 按下的时候
    self.slider.addTarget(self, action: #selector(self.sliderTouchDown), for: .touchDown)
  
    // 弹起的时候
     self.slider.addTarget(self, action: #selector(self.sliderTouchUpOut), for: .touchUpOutside)
     self.slider.addTarget(self, action: #selector(self.sliderTouchUpOut), for: .touchUpInside)
     self.slider.addTarget(self, action: #selector(self.sliderTouchUpOut), for: .touchCancel)
    
    self.progressView = UIProgressView()
    self.progressView.backgroundColor = UIColor.lightGray
    self.insertSubview(self.progressView, belowSubview: self.slider)
    self.progressView.tintColor = UIColor.red
    self.progressView.progress = 0
    
    self.playBtn = UIButton()
    self.playBtn.setImage(UIImage(named:"videopause_control_nor"), for: .normal)
    self.addSubview(self.playBtn)
    self.playBtn.addTarget(self, action: #selector(self.playBtnAction), for: .touchUpInside)
}

func sliderTouchDown(){
    self.sliding = true
}
func sliderTouchUpOut(){
    // 代理处理
    delegate?.wxplayer(playerView: self, slider: self.slider)
}

func updateUI(timeStr: String) {
    
    self.timeLabel.text = timeStr
    self.timeLabel.sizeToFit()
    self.setNeedsLayout()
}
func playBtnAction()
{
    self.playing = !self.playing // 改变状态
    
    // 根据状态设定图片
    if playing {
        playBtn.setImage(UIImage(named: "videopause_control_nor"), for: .normal)
    }else{
        playBtn.setImage(UIImage(named: "videoplay_control_nor"), for: .normal)
    }
    // 代理方法
    delegate?.wxplayer(playerView: self, playAndPause: self.playBtn)
}

override func layoutSubviews() {
    super.layoutSubviews()
    
    self.playerLayer.frame = self.bounds
    self.timeLabel.frame.origin.x = self.frame.width - self.timeLabel.frame.width - 5
    self.timeLabel.frame.origin.y = self.frame.height - self.timeLabel.frame.height - 50
    
    self.slider.frame.origin.x = 40
    self.slider.frame.origin.y = self.frame.height - 75
    self.slider.frame.size.width = self.frame.width - 140
    
    self.progressView.frame.origin.x = 42
    self.progressView.frame.origin.y = self.frame.height - 59
    self.progressView.frame.size.width =  self.frame.width - 142
    
    self.playBtn.frame = CGRect(x: 5, y: self.frame.height - 75, width: 30, height: 30)
}

}
</pre>

接下来是VC中的代码,主要是实现逻辑部分

<pre>import UIKit
import AVFoundation

extension ViewController: WXPlayerViewDelegate{

func wxplayer(playerView: WXPlayerView, slider: UISlider) {
    
    if self.avplayer.status == AVPlayerStatus.readyToPlay{
    
         let duration = slider.value * Float(CMTimeGetSeconds(self.avplayer.currentItem!.duration))
        let seekTime = CMTimeMake(Int64(duration), 1)
        self.avplayer.seek(to: seekTime, completionHandler: { (b) in
            
            playerView.sliding = false
        })
    }
}

func wxplayer(playerView: WXPlayerView, playAndPause playBtn: UIButton) {
    
    if !playerView.playing{
        self.avplayer.pause()
    }else{
        if self.avplayer.status == AVPlayerStatus.readyToPlay{
            self.avplayer.play()
        }
    }
}

}

class ViewController: UIViewController {
var playerView: WXPlayerView!
var playerItem: AVPlayerItem!
var avplayer: AVPlayer!
var playerLayer: AVPlayerLayer!
var link: CADisplayLink!

override func viewDidLoad() {
    super.viewDidLoad()
   
    self.initPlayer()
    self.link = CADisplayLink(target: self, selector: #selector(self.update))
    self.link.add(to: .main, forMode: RunLoopMode.defaultRunLoopMode)
}

deinit {
    
    self.playerItem.removeObserver(self, forKeyPath: "loadedTimeRanges")
    self.playerItem.removeObserver(self, forKeyPath: "status")
}

func initPlayer()
{
    let url = URL(string: "http://vt1.doubanio.com/201609291737/4af83e686c0432c0dbd3c320f14eba6f/view/movie/M/302030039.mp4")
    self.playerItem = AVPlayerItem(url: url!)
    self.playerItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
    self.playerItem.addObserver(self, forKeyPath: "status", options: .new, context: nil)
    self.avplayer = AVPlayer(playerItem: self.playerItem)
    self.playerLayer = AVPlayerLayer(player: self.avplayer)
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
    self.playerLayer.contentsScale = UIScreen.main.scale
    self.view.layer.addSublayer( self.playerLayer)
    
    self.playerView = WXPlayerView()
    self.playerView.delegate = self
    self.playerView.frame = CGRect(x: 0, y: 20, width: self.view.frame.width, height: 300)
    self.view.addSubview(self.playerView)
    self.playerView.playerLayer = self.playerLayer
    self.playerView.layer.insertSublayer(self.playerLayer, at: 0)
}

func update(){
    
    //暂停的时候
    if !self.playerView.playing{
        return
    }
    
    let currentTime = CMTimeGetSeconds(self.avplayer.currentTime())
    let totalTime = TimeInterval(self.playerItem.duration.value) / TimeInterval(self.playerItem.duration.timescale)
    let timeStr = "\(self.formatPlayTime(secounds: currentTime))/\(self.formatPlayTime(secounds: totalTime))"
    self.playerView.updateUI(timeStr: timeStr)
    if !self.playerView.sliding{
        // 播放进度
        self.playerView.slider.value = Float(currentTime/totalTime)
    }
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    
    if keyPath == "loadedTimeRanges"{
    
        // 通过监听AVPlayerItem的"loadedTimeRanges",可以实时知道当前视频的进度缓冲
        let loadedTime = avalableDurationWithplayerItem()
        let totalTime = CMTimeGetSeconds(playerItem.duration)
        let percent = loadedTime/totalTime // 计算出比例
        // 改变进度条
        self.playerView.progressView.progress = Float(percent)
    
    }else if keyPath == "status"{
    
        if self.playerItem.status == AVPlayerItemStatus.readyToPlay{
            
            self.avplayer.play()

        }else
        {
            print("加载异常")
        }
    }
}

func formatPlayTime(secounds: TimeInterval) -> String{
    if secounds.isNaN{
        
        return "00:00"
    }

    let min = Int(secounds / 60)
    let sec = Int(secounds.truncatingRemainder(dividingBy: 60) )
    return String(format: "%02d:%02d", min,sec)
}
// 计算当前缓冲进度
func avalableDurationWithplayerItem() -> TimeInterval{

    guard let loadedTimeRanges = self.avplayer.currentItem?.loadedTimeRanges,let first = loadedTimeRanges.first else {fatalError()}
    let timeRange = first.timeRangeValue
    let startSeconds = CMTimeGetSeconds(timeRange.start)
    let durationSecound = CMTimeGetSeconds(timeRange.duration)
    let result = startSeconds + durationSecound
    return result
}

}
</pre>
实现后的效果图

1.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容