iOS AVPlayer - swift视频播放

## AVPlayer的简单使用 ##
自己写得并不好(刚学swift,语法可能有点奇怪,偏向OC),只是试试看能不能有什么帮助吧。。。没有的话,下次努力
1.导入系统头文件 AVFoundation
2*.创建界面UI*
3.播放功能实现

这里是一些重要的代码片段

系统自带的avplayer的创建初始化

 //创建player
    *fileprivate func createPlayer() {
        playerItem = AVPlayerItem.init(url: NSURL.init(string: "http://krtv.qiniudn.com/150522nextapp") as! URL)
        playerItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
        player = AVPlayer.init(playerItem: playerItem)
        let playerLayer = AVPlayerLayer.init(player: player)
        playerLayer.frame = CGRect.init(x: 0, y: 0, width: screenW, height: screenH)
        playerLayer.videoGravity = AVLayerVideoGravityResize
        self.view.layer.addSublayer(playerLayer)
        player.play()

        addTimer()*

    }

下一个视频的实现。有兴趣可以试试只换url会产生什么效果.

//下一曲,这里应该重新创建 AVPlayerItem
    func nextVideo()  {
        // player = nil
        player.pause()
        removeTimer()
        playerItem.removeObserver(self, forKeyPath: "loadedTimeRanges", context: nil)
        playerItem = nil
        // player = nil
        let playerI = AVPlayerItem.init(url: NSURL.init(string: "http://wvideo.spriteapp.cn/video/2016/0328/56f8ec01d9bfe_wpd.mp4") as! URL)
        //
        player.replaceCurrentItem(with: playerI)

        // let play = AVPlayer.init(playerItem: playerI)
        // player = play
        playerItem = playerI
        playerItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
        player.play()
        addTimer()
    }

进度条,用观察者模式实现

func progressSliderValueChange()  {
        // 拖动改变视频播放进度
        if player.status == .readyToPlay {
            let total = Float(playerItem.duration.value/Int64(playerItem.duration.timescale))
            let dragedSeconds = floorf(total * progressSlider.value)

            let dragedCMTime = CMTime.init(value: CMTimeValue(dragedSeconds), timescale: 1)
            player.pause()
            removeTimer()
            player.seek(to: dragedCMTime, completionHandler: { (finish) in
                if finish  {
                    self.player.play()
                    self.addTimer()
                }
            })

        }
    }
    // 观察者模式 进行进度条的改变
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "loadedTimeRanges" {
            // let timeinterval = self.availableDuration()//缓冲速度
            let duration = playerItem.duration
            let total = CMTimeGetSeconds(duration)
            progress.setProgress(Float(total), animated: false)
        }

    }

下面是计算时间的方法,可以不看,相信有很多大神比我写的好

 func availableDuration() -> TimeInterval{
        let loadedTimeRanges = player.currentItem?.loadedTimeRanges
        let timeRange = loadedTimeRanges?.first?.timeRangeValue as CMTimeRange?
        let startSeconds = CMTimeGetSeconds(timeRange!.start)
        let durationSeconds = CMTimeGetSeconds(timeRange!.duration)
        let result = (startSeconds + durationSeconds)
        return result

    }
    //计算时间的方法
    func timerProgress()  {
        if playerItem.duration.timescale != 0 {
            progressSlider.maximumValue = 1.0
            let total = Float(playerItem.duration.value/Int64(playerItem.duration.timescale))
            progressSlider.value = Float(CMTimeGetSeconds(playerItem.currentTime()))/total
            let promin = NSInteger(CMTimeGetSeconds(playerItem.currentTime()))/60//当前秒
            let prosec = NSInteger(CMTimeGetSeconds(playerItem.currentTime()))%60//当前分

            let durmin = NSInteger(total)/60
            let dursec = NSInteger(total)%60

            let leftmin = durmin - promin
            let leftsec = dursec - prosec


            timeLable.text = NSString.init(format: "%02ld:%02ld", promin,prosec,durmin,dursec) as String

            leftLable.text = NSString.init(format: "-%02ld:%02ld", leftmin,leftsec) as String

        }
    }

Demo 的 github 地址 : https://github.com/aasdsjk/AVPlayer
avplayer的简单使用大概就是这样的了,项目中用的是第三方。。。这个是自己有空写的一个简单的demo
有兴趣的可以看一看

你可能感兴趣的:(ios,视频,swift,avplayer)