Skip to content

Instantly share code, notes, and snippets.

@bob910078
Created May 26, 2020 18:31
Show Gist options
  • Save bob910078/69d387ccec4897fed3e7dddab03b8a1f to your computer and use it in GitHub Desktop.
Save bob910078/69d387ccec4897fed3e7dddab03b8a1f to your computer and use it in GitHub Desktop.
NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChange(_:)), name: .AVAudioSessionRouteChange, object: nil)
@objc func audioRouteChange(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let rv = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSessionRouteChangeReason(rawValue: rv) else { return }
switch reason {
case .newDeviceAvailable:
let audioOutputs = AVAudioSession.sharedInstance().currentRoute.outputs
for output in audioOutputs where output.portType == AVAudioSessionPortHeadphones {
print("耳機已插入耳機孔")
}
case .oldDeviceUnavailable:
guard let previousRoute = userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription else { return }
for output in previousRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
print("耳機已拔出耳機孔")
}
default:
break
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment