Skip to content

Instantly share code, notes, and snippets.

@budidino
Last active March 11, 2017 03:25
Show Gist options
  • Save budidino/e0d4e353bc1e9a58caa67f450dc55f5c to your computer and use it in GitHub Desktop.
Save budidino/e0d4e353bc1e9a58caa67f450dc55f5c to your computer and use it in GitHub Desktop.
play video's audio out loud and resume playback after plugging out headphones
// SWIFT 2 - http://stackoverflow.com/a/42730969/611879
// setup player
let audioSession = AVAudioSession.sharedInstance()
_ = try? audioSession.setCategory(AVAudioSessionCategoryPlayback, withOptions: .DuckOthers)
_ = try? audioSession.setActive(true)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(audioRouteChanged), name: AVAudioSessionRouteChangeNotification, object: nil)
player.play()
// observer
func audioRouteChanged(note: NSNotification) {
if let userInfo = note.userInfo {
if let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? Int {
if reason == AVAudioSessionRouteChangeReason.OldDeviceUnavailable.hashValue {
// headphones plugged out -> continue playback
player.play()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment