You need to observe the hardware rout change observer and based on callback, You can just stop playing.
Setup your player - play audio (even on silent mode) and silence other music:
let audioSession = AVAudioSession.sharedInstance()
_ = try? audioSession.setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
_ = try? audioSession.setActive(true)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(audioRouteChanged), name: .AVAudioSessionRouteChange, object: nil)
func audioRouteChanged(note: Notification) {
if let userInfo = note.userInfo {
if let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? Int {
if reason == AVAudioSessionRouteChangeReason.oldDeviceUnavailable.hashValue {
// headphones plugged out
player.stop()
}
}
}
}
Important: Media playback apps should pause playback if the route change reason is AVAudioSessionRouteChangeReasonOldDeviceUnavailable, but should not if the reason is AVAudioSessionRouteChangeReasonOverride.