屏幕锁定时,AVPlayer无法切换到下一首曲目

时间:2018-07-11 03:02:35

标签: xcode swift3 avplayer avaudioplayer mpremotecommandcenter

我正在使用AVPlayer播放音频,正在播放音频,并且当应用程序处于后台并且屏幕锁定时,它会转到下一首曲目。我的问题是,每当屏幕变黑并且当前曲目播放完毕时,除非我唤醒屏幕然后跳至下一首曲目,否则下一首曲目将不会播放。我还设置了遥控器,并且工作正常。任何帮助将不胜感激,在此先感谢...

这就是我跳到下一首曲目的方式

NotificationCenter.default.addObserver(self, selector: #selector(audioFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: AVPlayerManager.instance.player.currentItem)

@objc func audioFinishPlaying(notification: NotificationCenter) {

    if repeatSelected == true {
        AVPlayerManager.instance.player.seek(to: kCMTimeZero)
        AVPlayerManager.instance.player.play()
    }

    else {

        let current = focusedAudioItem
        if current + 1 < subCategoryItems.count {
            let path  = IndexPath(item: current + 1, section: 0)
            self.collectionView.selectItem(at: path, animated: true, scrollPosition: .centeredHorizontally)
    }
        else {

            playBtn.setImage(#imageLiteral(resourceName: "play"), for: UIControlState.normal)
            AVPlayerManager.instance.player.seek(to: kCMTimeZero)
        }
   }

}

音频会话

func setupAudioSession() {

    let audioSession = AVAudioSession.sharedInstance()

    do {
        try audioSession.setCategory(AVAudioSessionCategoryPlayback)
        UIApplication.shared.beginReceivingRemoteControlEvents()
        try audioSession.setActive(true)

    } catch {

        print(error.localizedDescription)
    }
 }

0 个答案:

没有答案