iOS, Swift
Swift ) 전화, 이어폰 감지 ( AVAudioSession ) - EEYatHo iOS
EEYatHo
2021. 8. 24. 14:27
전화온거 감지. ( 인터럽트 발생 및 감지 )
1. import
import AVFoundation
2. 노티 옵저버 추가 ( AVAudioSession.interruptionNotification )
NotificationCenter.default.addObserver(self,
selector: #selector(handleInterruptionOccured(notification:)),
name: AVAudioSession.interruptionNotification,
object: AVAudioSession.sharedInstance())
3. 처리 로직
@objc private func handleInterruptionOccured(notification: Notification) {
let interruptionType = notification.userInfo![AVAudioSessionInterruptionTypeKey] as! AVAudioSession.InterruptionType
if interruptionType == .began {
// 전화(Interruption)가 시작될 때 처리 코드
} else {
let options = notification.userInfo![AVAudioSessionInterruptionOptionKey] as! AVAudioSession.InterruptionOptions
if options == .shouldResume {
// 전화가 끊겼을 때 처리 코드
}
}
}
이어폰 감지. ( Route가 변화하는 것을 감지 )
1. import
import AVFoundation
2. 노티 옵저버 추가 ( AVAudioSession.routeChangeNotification )
NotificationCenter.default.addObserver(self,
selector: #selector(handleRouteChanged(notification:)),
name: AVAudioSession.routeChangeNotification,
object: AVAudioSession.sharedInstance())
3. 처리 로직 ( 이어폰 빠졌을 때 재생 멈춤 등 별도 처리 )
@objc private func handleRouteChanged(notification: Notification) {
let info = notification.userInfo!
let reason = info[AVAudioSessionRouteChangeReasonKey] as! AVAudioSession.RouteChangeReason
if reason == .oldDeviceUnavailable {
let prevRoute = info[AVAudioSessionRouteChangePreviousRouteKey]. as! AVAudioSessionRouteDescription
let prevOutput = prevRoute.outputs[0]
let portType = prevOutput.portType
if portType == .headphones {
// 제거된 디바이스가 이어폰이다 -> 영상이나 음악 재생 멈추는 코드
}
}
}
반응형