移除耳机时防止视频暂停

时间:2016-12-09 07:21:04

标签: ios swift xcode avaudiosession headset

使用的语言:Swift 2.3

我正在使用AVPlayerViewController,这是我的代码

let player = AVPlayer(URL: videoUrl!)            
playerViewController.player = player
playerViewController.showsPlaybackControls = false

我在这里做的是我正在播放的视频应该是不可原谅的和不可克服的。

此处我正在使用NSNotificationCenter

监控视频是否已结束
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.actionAfterVideo), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)

然后会解雇我的AVPlayerViewController

func actionAfterVideo() {
    playerViewController.dismissViewControllerAnimated(true, completion: nil)
}

除非用户插入并拔下耳机,否则所有这些都能正常工作。这会自动暂停视频。他们当然可以使用Control Center恢复它,但这不是直观的。

当我从手机上拔下耳机时,我是否可以阻止视频暂停?

1 个答案:

答案 0 :(得分:2)

您可以添加通知以检查会话是否已被中断,如下所示:

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "playInterrupt:", name: AVAudioSessionInterruptionNotification, object: yourSession)

并添加其playInterrupt实现,如下所示:

func playInterrupt(notification: NSNotification)
{
    if notification.name == AVAudioSessionInterruptionNotification && notification.userInfo != nil
    {
        var info = notification.userInfo!
        var intValue: UInt = 0

        (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)

        if let type = AVAudioSessionInterruptionType(rawValue: intValue)
        {
            switch type
            {
            case .Began:
                player.pause()
            case .Ended:
                let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
            }
        }
    }
}

func resumeNow(timer : NSTimer)
{
    player.play()
    print("restart")
}

另请查看Apple's documentation