Zonily Jame
Zonily Jame

Reputation: 5359

Preventing video pause when headset is removed

Language Used: Swift 2.3

I am using AVPlayerViewController and here's my code

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

What I'm doing here is I'm playing a Video that is supposed to be unpausable and unskippable.

Here I'm monitoring if the video has ended using NSNotificationCenter

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.actionAfterVideo), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)

Which would then dismiss my AVPlayerViewController

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

All of these works perfectly fine except when a user plugs and unplugs a headset. This automatically pauses the video. They could resume it of course by using the Control Center but that wouldn''t be intuitive.

Is there anyway I could prevent the video from pausing when a headset is unplugged from the phone?

Upvotes: 0

Views: 806

Answers (1)

Munahil
Munahil

Reputation: 2419

You can add a notification to check if session has been interrupted like this :

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

And add its playInterrupt implementation like this :

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")
}

Also have a look at Apple's documentation

Upvotes: 2

Related Questions