Created
May 26, 2020 18:31
-
-
Save bob910078/69d387ccec4897fed3e7dddab03b8a1f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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