Reputation: 139
How can I detect, from within my application, if an external microphone is plugged in the device?
Upvotes: 2
Views: 3391
Reputation: 194
swift3:
NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListener(notification:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil)
@objc private func audioRouteChangeListener(notification: Notification) {
let rawReason = notification.userInfo![AVAudioSessionRouteChangeReasonKey] as! UInt
let reason = AVAudioSessionRouteChangeReason(rawValue: rawReason)!
switch reason {
case .newDeviceAvailable:
print("headphone plugged in")
case .oldDeviceUnavailable:
print("headphone pulled out")
default:
break
}
}
Upvotes: 1
Reputation: 38162
Try this:
let route = AVAudioSession.sharedInstance().currentRoute
for port in route.outputs {
if port.portType == AVAudioSessionPortHeadphones {
// Headphones located
}
}
EDIT: Post OP change in question -
When app is running you need to register for AVAudioSessionRouteChangeNotification
to listen to the changes like this:
NSNotificationCenter.defaultCenter().addObserver(self, selector:"audioRouteChangeListener:", name: AVAudioSessionRouteChangeNotification, object: nil)
dynamic private func audioRouteChangeListener(notification:NSNotification) {
let audioRouteChangeReason = notification.userInfo![AVAudioSessionRouteChangeReasonKey] as UInt
switch audioRouteChangeReason {
case AVAudioSessionRouteChangeReason.NewDeviceAvailable.rawValue:
println("headphone plugged in")
case AVAudioSessionRouteChangeReason.OldDeviceUnavailable.rawValue:
println("headphone pulled out")
default:
break
}
}
Upvotes: 4
Reputation: 151
With AVAudioSession
you can list the availableInputs
let session = AVAudioSession.sharedInstance()
_ = try? session.setCategory(AVAudioSessionCategoryRecord, withOptions: [])
print(AVAudioSession.sharedInstance().availableInputs)
It return an array of AVAudioSessionPortDescription
. And you can have the portType "wired or builtIn" microphone type.
PS : It only work on real device not on simulator.
Upvotes: 1
Reputation: 4917
With swift 2.0 this code works
func audioRouteChangeListenerCallback (notif: NSNotification){
let userInfo:[NSObject:AnyObject] = notif.userInfo!
let routChangeReason = UInt((userInfo[AVAudioSessionRouteChangeReasonKey]?.integerValue)!)
switch routChangeReason {
case AVAudioSessionRouteChangeReason.NewDeviceAvailable.rawValue:
print("Connected");
break;
case AVAudioSessionRouteChangeReason.OldDeviceUnavailable.rawValue:
do {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
} catch _ {
}
print("Connected");
break;
case AVAudioSessionRouteChangeReason.CategoryChange.rawValue:
break;
default:
break;
}
}
Upvotes: 0