swift-问题栈

视频播放器AVPlayer的封装

2016-06-02  本文已影响106人  zeroLL

使用代码就是这么简单

let vv = HYPlayer(frame: CGRectMake(0, 100, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.width*9/16), url: "http://v1.mukewang.com/57de8272-38a2-4cae-b734-ac55ab528aa8/L.mp4")
self.view.addSubview(vv)

使用演示


源代码下载github

HYVideoPlayerControlView

import UIKit

let ideoControlBarHeight:CGFloat = 40.0
let ideoControlAnimationTimeInterval:NSTimeInterval = 0.3
let ideoControlTimeLabelFontSize:CGFloat = 10.0
let ideoControlBarAutoFadeOutTimeInterval:NSTimeInterval = 10.0

protocol HYVideoPlayerControlViewDelegate {
   func videoPlayerControlView(playerControlView:HYVideoPlayerControlView, slideRight startTouchPosition:CGPoint,     distance dis:CGFloat)
   func videoPlayerControlView(playerControlView:HYVideoPlayerControlView, slideLeft startTouchPosition:CGPoint, distance dis:CGFloat)
   func videoPlayerControlView(playerControlView:HYVideoPlayerControlView, slideTop startTouchPosition:CGPoint, distance dis:CGFloat)
   func videoPlayerControlView(playerControlView:HYVideoPlayerControlView, slideBottom startTouchPosition:CGPoint, distance dis:CGFloat)
   func videoPlayerControlViewTouchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
}

class HYVideoPlayerControlView: UIView {

   var topBar:UIView = {
      let _topBar = UIView()
      _topBar.backgroundColor = UIColor.clearColor()
      return _topBar
   }()

   var bottomBar:UIView = {
      let _bottomBar = UIView()
      _bottomBar.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
      return _bottomBar
   }()

   var playButton:UIButton = {
      let _playButton = UIButton(type: UIButtonType.Custom)
      _playButton.setImage(UIImage(named:"kr-video-player-play"), forState: .Normal)
      _playButton.bounds = CGRectMake(0, 0, ideoControlBarHeight, ideoControlBarHeight)
      return _playButton
   }()

   var pauseButton:UIButton = {
      let _pauseButton = UIButton(type: UIButtonType.Custom)
      _pauseButton.setImage(UIImage(named:"kr-video-player-pause"), forState: .Normal)
      _pauseButton.bounds = CGRectMake(0, 0, ideoControlBarHeight, ideoControlBarHeight)
      return _pauseButton
   }()

   var fullScreenButton:UIButton = {
      let _fullScreenButton = UIButton(type: UIButtonType.Custom)
      _fullScreenButton.setImage(UIImage(named:"kr-video-player-fullscreen"), forState: .Normal)
      _fullScreenButton.bounds = CGRectMake(0, 0, ideoControlBarHeight, ideoControlBarHeight)
      return _fullScreenButton
   }()

   var shrinkScreenButton:UIButton = {
      let _shrinkScreenButton = UIButton(type: UIButtonType.Custom)
      _shrinkScreenButton.setImage(UIImage(named:"kr-video-player-shrinkscreen"), forState: .Normal)
      _shrinkScreenButton.bounds = CGRectMake(0, 0, ideoControlBarHeight, ideoControlBarHeight)
      return _shrinkScreenButton
   }()

   var progressSlider:UISlider = {
      let _progressSlider = UISlider()
      _progressSlider.setThumbImage(UIImage(named:"kr-video-player-point"), forState: .Normal)
      _progressSlider.minimumTrackTintColor = UIColor.whiteColor()
      _progressSlider.maximumTrackTintColor = UIColor.lightGrayColor()
      _progressSlider.value = 0
      _progressSlider.continuous = true
      return _progressSlider
   }()

   var closeButton:UIButton = {
      let _closeButton = UIButton(type: UIButtonType.Custom)
      _closeButton.setImage(UIImage(named:"kr-video-player-close"), forState: .Normal)
      _closeButton.bounds = CGRectMake(0, 0, ideoControlBarHeight, ideoControlBarHeight)
      return _closeButton
   }()

   var timeLabel:UILabel = {
      let _timeLabel = UILabel()
      _timeLabel.backgroundColor = UIColor.clearColor()
      _timeLabel.font = UIFont.systemFontOfSize(ideoControlTimeLabelFontSize)
      _timeLabel.textColor = UIColor.whiteColor()
      _timeLabel.textAlignment = NSTextAlignment.Right
      _timeLabel.bounds = CGRectMake(0, 0, ideoControlTimeLabelFontSize, ideoControlTimeLabelFontSize)
      return _timeLabel
   }()

   var indicatorView:UIActivityIndicatorView = {
      let _indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
      _indicatorView.stopAnimating()
      return _indicatorView
   }()

   var isBarShowing = false
   var delegate:HYVideoPlayerControlViewDelegate?

   override init(frame: CGRect) {
      super.init(frame: frame)
  
      self.backgroundColor = UIColor.clearColor()
      self.addSubview(self.topBar)
      //close button
//      self.topBar.addSubview(self.closeButton)
      self.addSubview(self.bottomBar)
      self.bottomBar.addSubview(self.playButton)
      self.bottomBar.addSubview(self.pauseButton)
      self.pauseButton.hidden = true
      self.bottomBar.addSubview(self.fullScreenButton)
      self.bottomBar.addSubview(self.shrinkScreenButton)
      self.shrinkScreenButton.hidden = true
      self.bottomBar.addSubview(self.progressSlider)
      self.bottomBar.addSubview(self.timeLabel)
      self.addSubview(self.indicatorView)
      let tapGesture = UITapGestureRecognizer(target: self, action: #selector(HYVideoPlayerControlView.onTap(_:)))
  
      self.addGestureRecognizer(tapGesture)
   }

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

   override func layoutSubviews() {
      super.layoutSubviews()
      self.topBar.frame = CGRectMake(CGRectGetMinX(self.bounds), CGRectGetMinY(self.bounds), CGRectGetWidth(self.bounds), ideoControlBarHeight)
      self.closeButton.frame = CGRectMake(CGRectGetWidth(self.topBar.bounds) - CGRectGetWidth(self.closeButton.bounds), CGRectGetMinX(self.topBar.bounds), CGRectGetWidth(self.closeButton.bounds), CGRectGetHeight(self.closeButton.bounds))
      self.bottomBar.frame = CGRectMake(CGRectGetMinX(self.bounds), CGRectGetHeight(self.bounds) - ideoControlBarHeight, CGRectGetWidth(self.bounds), ideoControlBarHeight)
      self.playButton.frame = CGRectMake(CGRectGetMinX(self.bottomBar.bounds), CGRectGetHeight(self.bottomBar.bounds)/2 - CGRectGetHeight(self.playButton.bounds)/2, CGRectGetWidth(self.playButton.bounds), CGRectGetHeight(self.playButton.bounds))
      self.pauseButton.frame = self.playButton.frame
      self.fullScreenButton.frame = CGRectMake(CGRectGetWidth(self.bottomBar.bounds) - CGRectGetWidth(self.fullScreenButton.bounds), CGRectGetHeight(self.bottomBar.bounds)/2 - CGRectGetHeight(self.fullScreenButton.bounds)/2, CGRectGetWidth(self.fullScreenButton.bounds), CGRectGetHeight(self.fullScreenButton.bounds))
      self.shrinkScreenButton.frame = self.fullScreenButton.frame
      self.progressSlider.frame = CGRectMake(CGRectGetMaxX(self.playButton.frame), CGRectGetHeight(self.bottomBar.bounds)/2 - CGRectGetHeight(self.progressSlider.bounds)/2, CGRectGetMinX(self.fullScreenButton.frame) - CGRectGetMaxX(self.playButton.frame), CGRectGetHeight(self.progressSlider.bounds))
      self.timeLabel.frame = CGRectMake(CGRectGetMidX(self.progressSlider.frame), CGRectGetHeight(self.bottomBar.bounds) - CGRectGetHeight(self.timeLabel.bounds) - 2.0, CGRectGetWidth(self.progressSlider.bounds)/2, CGRectGetHeight(self.timeLabel.bounds))
      self.indicatorView.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
      self.indicatorView.frame.size = CGSize(width: 30, height: 30)
   }

   override func didMoveToSuperview() {
      super.didMoveToSuperview()
      self.isBarShowing = true
   }

   func animateHide(){
      if (!self.isBarShowing) {
         return
      }
      UIView.animateWithDuration(ideoControlAnimationTimeInterval, animations: {
         self.topBar.alpha = 0.0
         self.bottomBar.alpha = 0.0
      }) { (finished) in
         self.isBarShowing = false
      }
   }

   func animateShow(){
      if (self.isBarShowing) {
         return
      }
      UIView.animateWithDuration(ideoControlAnimationTimeInterval, animations: {
         self.topBar.alpha = 1.0
         self.bottomBar.alpha = 1.0
      }) { (finished) in
         self.isBarShowing = true
         self.autoFadeOutControlBar()
      }
   }

   func autoFadeOutControlBar(){
      if (!self.isBarShowing) {
         return
      }
      NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: #selector(animateHide), object: nil)
      self.performSelector(#selector(animateHide), withObject: nil, afterDelay: ideoControlBarAutoFadeOutTimeInterval)
   }

   func cancelAutoFadeOutControlBar(){
      NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: #selector(animateHide), object: nil)
   }

   func onTap(gesture:UITapGestureRecognizer){
      if gesture.state == .Recognized{
         if (self.isBarShowing) {
            self.animateHide()
         } else {
            self.animateShow()
         }
      }
   }

   let HORIZ:CGFloat = 12
   let VERT:CGFloat = 10

   var startTouchPosition:CGPoint!
   var dirString:NSString = ""

   override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
      let touch = touches.first!
      startTouchPosition = touch.locationInView(self)
   }

   override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
      let touch = touches.first!
      let currentTouchPosition = touch.locationInView(self)
  
      let scX = startTouchPosition.x - currentTouchPosition.x
      let scY = startTouchPosition.y - currentTouchPosition.y
  
      if scX >= HORIZ && !(scY <= -VERT || scY >= VERT){
         if scX > 20{
            delegate?.videoPlayerControlView(self, slideLeft: startTouchPosition, distance: scX)
            startTouchPosition = currentTouchPosition
            animateShow()
         }
      }else if scX <= -HORIZ && !(scY <= -VERT || scY >= VERT){
         if scX < -20{
            delegate?.videoPlayerControlView(self, slideRight: startTouchPosition, distance: -scX)
            startTouchPosition = currentTouchPosition
            animateShow()
         }
      }else if scY >= HORIZ && !(scX <= -VERT || scX >= VERT){
         if scY > 20{
            delegate?.videoPlayerControlView(self, slideTop: startTouchPosition, distance: scY)
            startTouchPosition = currentTouchPosition
         }
      }else if scY <= -HORIZ && !(scX <= -VERT || scX >= VERT){
         if scY < -20{
            delegate?.videoPlayerControlView(self, slideBottom: startTouchPosition, distance: -scY)
            startTouchPosition = currentTouchPosition
         }
      }
   }

   override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
      delegate?.videoPlayerControlViewTouchesEnded(touches, withEvent: event)
   }
}

HYPlayer

import UIKit
import AVFoundation
import MediaPlayer

let ideoPlayerControllerAnimationTimeInterval = 0.3

class HYPlayer: UIView,HYVideoPlayerControlViewDelegate {

   var videoControl:HYVideoPlayerControlView = {
      let _videoControl = HYVideoPlayerControlView()
      return _videoControl
   }()

   var viewFrame:CGRect{
      get{
         return self.frame
      }
      set{
         self.frame = newValue
         self.videoControl.frame = CGRectMake(0, 0, newValue.size.width, newValue.size.height)
         self.videoControl.setNeedsLayout()
         self.videoControl.layoutIfNeeded()
      }
   }

   // 成员变量
   var player:AVPlayer!
   var playLayer:AVPlayerLayer!
   var playerItem:AVPlayerItem!
   var isFullscreenMode = false
   var originFrame:CGRect = CGRectZero
   var durationTimer:NSTimer!

   init(frame: CGRect,url:String) {
      super.init(frame:frame)
  
      let remoteURL = NSURL(string: url)
  
      playerItem = AVPlayerItem(URL: remoteURL!)
      self.playerItem.addObserver(self, forKeyPath: "status", options: .New, context: nil)// 监听status属性
      self.playerItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: .New, context: nil)// 监听loadedTimeRanges属性
      self.playerItem.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .New, context: nil)// 监听loadedTimeRanges属性
      self.playerItem.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .New, context: nil)// 监听loadedTimeRanges属性
  
      NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.myMovieFinishedCallback(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: self.playerItem)//监听播放结束

      player = AVPlayer(playerItem: playerItem)
  
      playLayer = AVPlayerLayer(player: player)
      playLayer.frame = CGRectMake(0, 0, frame.size.width, frame.size.height)
  
      self.layer.addSublayer(playLayer)
  
      viewFrame = frame
      self.addSubview(videoControl)
      videoControl.delegate = self
      self.backgroundColor = UIColor.whiteColor()
  
      configControlAction()
   }

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

   func dismiss(){
      self.stopDurationTimer()
      player.pause()
      UIView.animateWithDuration(ideoPlayerControllerAnimationTimeInterval, animations: {
         self.alpha = 0.0
      }) { (finished) in
         self.removeFromSuperview()
         //self.dimissCompleteBlock()
      }
   }

   //MARK: - 基础配置,给按钮添加事件

   func configControlAction(){
      self.videoControl.playButton.addTarget(self, action: #selector(playButtonClick), forControlEvents: .TouchUpInside)
      self.videoControl.pauseButton.addTarget(self, action: #selector(pauseButtonClick), forControlEvents: .TouchUpInside)
      self.videoControl.closeButton.addTarget(self, action: #selector(closeButtonClick), forControlEvents: .TouchUpInside)
      self.videoControl.fullScreenButton.addTarget(self, action: #selector(fullScreenButtonClick), forControlEvents: .TouchUpInside)
      self.videoControl.shrinkScreenButton.addTarget(self, action: #selector(shrinkScreenButtonClick), forControlEvents: .TouchUpInside)
  
      self.videoControl.progressSlider.addTarget(self, action: #selector(self.progressSliderValueChanged(_:)), forControlEvents: .ValueChanged)
      self.videoControl.progressSlider.addTarget(self, action: #selector(self.progressSliderTouchBegan(_:)), forControlEvents: .TouchDown)
      self.videoControl.progressSlider.addTarget(self, action: #selector(self.progressSliderTouchEnded(_:)), forControlEvents: .TouchUpInside)
      self.videoControl.progressSlider.addTarget(self, action: #selector(self.progressSliderTouchEnded(_:)), forControlEvents: .TouchUpOutside)
      self.videoControl.progressSlider.addTarget(self, action: #selector(self.progressSliderTouchEnded(_:)), forControlEvents: .TouchCancel)
      self.monitorVideoPlayback()
   }

   //MARK: - 各种按钮事件

   func playButtonClick(){
      player.play()
      self.videoControl.playButton.hidden = true
      self.videoControl.pauseButton.hidden = false
   }

   func pauseButtonClick(){
      player.pause()
      self.videoControl.playButton.hidden = false
      self.videoControl.pauseButton.hidden = true
   }    

   func closeButtonClick(){
      self.dismiss()
   }

   func fullScreenButtonClick(){
      if (self.isFullscreenMode) {
         return
      }
  
      self.originFrame = self.frame
      UIApplication.sharedApplication().statusBarOrientation = .LandscapeRight
      UIApplication.sharedApplication().keyWindow?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
      UIApplication.sharedApplication().statusBarHidden = true
  
  
      let height = UIScreen.mainScreen().bounds.size.width
      let width = UIScreen.mainScreen().bounds.size.height
  
      let frame = CGRectMake((width - height) / 2, (height - width) / 2, height, width)
      UIView.animateWithDuration(0.3, animations: {
         self.frame = frame
         let layerFrame = CGRectMake(0, 0, frame.size.width, frame.size.height)
         self.playLayer.frame = layerFrame
         self.videoControl.frame = layerFrame
         self.transform = CGAffineTransformMakeRotation(-CGFloat(M_PI_2))
      }) { (finished) in
         self.isFullscreenMode = true
         self.videoControl.fullScreenButton.hidden = true
         self.videoControl.shrinkScreenButton.hidden = false
      }
   }

   func shrinkScreenButtonClick(){
      if (!self.isFullscreenMode) {
         return
      }
      UIApplication.sharedApplication().statusBarOrientation = .Portrait
      UIApplication.sharedApplication().keyWindow?.transform = CGAffineTransformIdentity
      UIApplication.sharedApplication().statusBarHidden = false
  
      UIView.animateWithDuration(0.3, animations: {
         self.transform = CGAffineTransformIdentity
         self.frame = self.originFrame
         let layerFrame = CGRectMake(0, 0, self.originFrame.size.width, self.originFrame.size.height)
         self.playLayer.frame = layerFrame
         self.videoControl.frame = layerFrame
      }) { (finished) in
         self.isFullscreenMode = false
         self.videoControl.fullScreenButton.hidden = false
         self.videoControl.shrinkScreenButton.hidden = true
      }
   }

   //MARK: - progressSlider事件

   func progressSliderTouchBegan(slider:UISlider){
      player.pause()
      self.stopDurationTimer()
      self.videoControl.cancelAutoFadeOutControlBar()
   }

   func progressSliderTouchEnded(slider:UISlider){
      playButtonClick()
      self.startDurationTimer()
   }

   func progressSliderValueChanged(slider:UISlider){
      let currentTime = Double(floor(slider.value))
      let totalTime = Double(playerItem.duration.value)/Double(playerItem.duration.timescale)
      self.setTimeLabelValues(currentTime, totalTime: totalTime)
  
      let newTime = CMTimeMakeWithSeconds(Double(slider.value), 1000)
      player.seekToTime(newTime)
   }    

   //MARK: - KVO

   override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
      if let playerItem = object as? AVPlayerItem{
         if keyPath == "status" && playerItem == self.playerItem{
            if playerItem.status == .ReadyToPlay{
               // 获取视频总长度
               let value = Float(playerItem.duration.value)
               let timescale = Float(playerItem.duration.timescale)
               let duration:Float =  value / timescale
               self.videoControl.progressSlider.minimumValue = 0
               self.videoControl.progressSlider.maximumValue = Float(ceil(duration))
           
               self.videoControl.pauseButton.hidden = false
               self.videoControl.playButton.hidden = true
               self.startDurationTimer()
           
               self.videoControl.autoFadeOutControlBar()
               player.play()
           
            }else if playerItem.status == .Failed{
//               print("AVPlayerStatusFailed")
            }
         }else if keyPath == "loadedTimeRanges" && playerItem == self.playerItem{
//            print("loadedTimeRanges")
         }else if keyPath == "playbackBufferEmpty" && playerItem == self.playerItem{
            if (playerItem.playbackBufferEmpty) {
               self.videoControl.indicatorView.startAnimating()
//               print("playbackBufferEmpty")
            }
         }else if keyPath == "playbackLikelyToKeepUp" && playerItem == self.playerItem{
            if (playerItem.playbackLikelyToKeepUp)
            {
               self.videoControl.indicatorView.stopAnimating()
//               print("playbackLikelyToKeepUp")
            }
         }
      }
   }

   //MARK: - 播放结束事件

   func myMovieFinishedCallback(playItem:AVPlayerItem){
      self.videoControl.pauseButton.hidden = true
      self.videoControl.playButton.hidden = false
      self.stopDurationTimer()
      self.videoControl.animateShow()
  
      //回到初始状态
      player.seekToTime(CMTimeMakeWithSeconds(0, 1000))
      pauseButtonClick()
      let currentTime:Double = 0
      let totalTime = Double(playerItem.duration.value)/Double(playerItem.duration.timescale)
      self.setTimeLabelValues(currentTime, totalTime: totalTime)
      self.videoControl.progressSlider.value = 0
   }

   //MARK: - 定时器事件

   func monitorVideoPlayback(){
      let ctime = player.currentTime()
      let currentTime = Double(ctime.value)/Double(ctime.timescale)
      var totalTime:Double = 0
      if playerItem.duration.timescale != 0{
         totalTime = Double(playerItem.duration.value)/Double(playerItem.duration.timescale)
      }
  
      self.setTimeLabelValues(currentTime, totalTime: totalTime)
      self.videoControl.progressSlider.value = Float(ceil(currentTime))
   }

   //MARK: - 设置显示时间

   func setTimeLabelValues(currentTime:Double,totalTime:Double){
      let minutesElapsed = floor(currentTime / 60.0) ?? 0
      let secondsElapsed = fmod(currentTime, 60.0) ?? 0
      let timeElapsedString:NSString = NSString(format: "%02.0f:%02.0f", minutesElapsed,secondsElapsed)
  
      let minutesRemaining = floor(totalTime / 60.0)
      let secondsRemaining = floor(fmod(totalTime, 60.0))
      let timeRmainingString = NSString(format: "%02.0f:%02.0f", minutesRemaining,secondsRemaining)
  
      self.videoControl.timeLabel.text = NSString(format: "%@/%@", timeElapsedString,timeRmainingString) as String
   }

   //MARK: - 启动定时器

   func startDurationTimer(){
      if self.durationTimer == nil || !self.durationTimer.valid{
         self.durationTimer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: #selector(monitorVideoPlayback), userInfo: nil, repeats: true)
         NSRunLoop.currentRunLoop().addTimer(self.durationTimer, forMode: NSDefaultRunLoopMode)
      }
   }

   //MARK: - 关闭定时器

   func stopDurationTimer(){
      if self.durationTimer.valid{
         self.durationTimer.invalidate()
      }
   }

   func fadeDismissControl(){
      self.videoControl.animateHide()
   }

   //MARK: - 计算缓冲,暂未用到
 
   func availableDuration() -> NSTimeInterval{
      let loadedTimeRanges = player.currentItem?.loadedTimeRanges
      let timeRange = loadedTimeRanges?.first?.CMTimeRangeValue// 获取缓冲区域
      let startSeconds = CMTimeGetSeconds((timeRange?.start)!)
      let durationSeconds = CMTimeGetSeconds(timeRange!.duration)
      let result = startSeconds + durationSeconds// 计算缓冲总进度
      return result
   }

   func cancelObserver(){
      NSNotificationCenter.defaultCenter().removeObserver(self)
   }

   //MARK: - deinit

   deinit{
      stopDurationTimer()
      self.cancelObserver()
   }

   //MARK: - HYVideoPlayerControlViewDelegate

   enum slideDirection {
      case Right
      case Left
      case Top
      case Bottom
   }

   func videoPlayerControlView(playerControlView:HYVideoPlayerControlView, slideRight startTouchPosition:CGPoint, distance dis:CGFloat){
      slide(direction: .Right)
     }

   func videoPlayerControlView(playerControlView:HYVideoPlayerControlView, slideLeft startTouchPosition:CGPoint, distance dis:CGFloat){
      slide(direction: .Left)
   }

   func videoPlayerControlView(playerControlView:HYVideoPlayerControlView, slideTop startTouchPosition:CGPoint, distance dis:CGFloat){
      slide(startTouchPosition, playerControlView: playerControlView, direction: .Top)
   }

   func videoPlayerControlView(playerControlView:HYVideoPlayerControlView, slideBottom startTouchPosition:CGPoint, distance dis:CGFloat){
      slide(startTouchPosition, playerControlView: playerControlView, direction: .Bottom)
   }

   func videoPlayerControlViewTouchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?){
      self.startDurationTimer()
      player.play()
   }

   func slide(startTouchPosition:CGPoint = CGPointZero, playerControlView:HYVideoPlayerControlView? = nil ,direction:slideDirection){
      if direction == .Right || direction == .Left{
     
         self.stopDurationTimer()
         player.pause()
     
         let ctime = player.currentTime()
         let currentTime = direction == .Right ? Double(ctime.value)/Double(ctime.timescale) + 10:Double(ctime.value)/Double(ctime.timescale) - 10
         let totalTime = Double(playerItem.duration.value)/Double(playerItem.duration.timescale)
         let seconds = direction == .Right ? Double(self.videoControl.progressSlider.value) + 10:Double(self.videoControl.progressSlider.value) - 10
         self.setTimeLabelValues(currentTime>0 ? currentTime:0, totalTime: totalTime)
         self.videoControl.progressSlider.value = Float(ceil(currentTime))
         let newTime = CMTimeMakeWithSeconds(seconds, 1000)
         player.seekToTime(newTime)
      }else{
         if startTouchPosition.x > playerControlView!.frame.size.width/2{
            let vol = AVAudioSession.sharedInstance().outputVolume
            let volumeView = MPVolumeView()
        
            //find the volumeSlider
            for view in volumeView.subviews{
               if let slider = view as? UISlider{
                  direction == .Top ? slider.setValue(vol + 0.08, animated: true):slider.setValue(vol - 0.08, animated: true)
                  slider.sendActionsForControlEvents(.TouchUpInside)
               }
            }
         }else{
            if direction == .Top{
               UIScreen.mainScreen().brightness += 0.1
            }else{
               UIScreen.mainScreen().brightness -= 0.1
            }
         }
      }
   }
}
上一篇下一篇

猜你喜欢

热点阅读