应用程序运行或闲置15分钟时,AVPlayer层显示空白屏幕

时间:2016-07-25 16:47:47

标签: ios swift2 avfoundation avplayer avplayerlayer

我想使用AVPlayer()AVPlayerLayer()类创建自定义视频播放器。 我的代码适用于应用程序重新启动但出错并在应用程序运行或闲置超过15分钟时显示空白屏幕。 当发生此问题时,我的应用程序的所有类都有AVPlayerLayer显示空白屏幕。我不知道为什么会这样。

AVPlayer()和AVPlayerlayer()实例初始化如下。

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.


        dispatch_async(dispatch_get_main_queue(), { 

            let playerItem = AVPlayerItem(URL: self.itemUrl)
            self.avPlayer = AVPlayer(playerItem: playerItem)
            NSNotificationCenter.defaultCenter().addObserver(self,
                selector: #selector(VideoPreviewView.restartVideoFromBeginning),
                name: AVPlayerItemDidPlayToEndTimeNotification,
                object: self.avPlayer.currentItem)
            self.avPlayerLayer = AVPlayerLayer(player: self.avPlayer)
            self.view.layer.addSublayer(self.avPlayerLayer)
            self.avPlayerLayer.frame = self.view.bounds
            self.avPlayer.pause()
        })

    }
}

播放功能

func playVideo(sender: AnyObject) {

    avPlayer.play()
    if (avPlayer.rate != 0 && avPlayer.error == nil) {
        print("playing")
    }
    slider.hidden=false
    myTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(VideoPreviewView.updateSlider), userInfo: nil, repeats: true)
    slider.addTarget(self, action: #selector(VideoPreviewView.sliderValueDidChange(_: )), forControlEvents: UIControlEvents.ValueChanged)
    slider.minimumValue = 0.0
    slider.continuous = true
    pauseButton.hidden=false
    playButton.hidden=true
    closeViewButton.hidden = false
}

重新启动视频

func restartVideoFromBeginning() {

    let seconds: Int64 = 0
    let preferredTimeScale: Int32 = 1
    let seekTime: CMTime = CMTimeMake(seconds, preferredTimeScale)
    avPlayer?.seekToTime(seekTime)
    avPlayer?.pause()
    pauseButton.hidden=true
    playButton.hidden = false
    closeViewButton.hidden=false
}
func updateSlider() {
    if (avPlayer.rate != 0 && avPlayer.error == nil) {
        print("playing")
    }
    else{
        print("Not playing.")
    }
    currentTime = Float(CMTimeGetSeconds(avPlayer.currentTime()))
    duration = avPlayer.currentItem!.asset.duration
    totalDuration = Float(CMTimeGetSeconds(duration))
    slider.value = currentTime // Setting slider value as current time
    slider.maximumValue = totalDuration // Setting maximum value as total duration of the video
}
 func sliderValueDidChange(sender: UISlider!) {
    timeInSecond=slider.value
    newtime = CMTimeMakeWithSeconds(Double(timeInSecond), 1)// Setting new time using slider value
    avPlayer.seekToTime(newtime)
}
@IBAction func closeViewAction(sender: AnyObject) {
    pauseButton.hidden=true
    self.avPlayer.pause()

    self.avPlayerLayer.removeFromSuperlayer()
    self.dismissViewControllerAnimated(true, completion: nil)


}

0 个答案:

没有答案