如何在 iOS 中检测外部麦克风?
Posted
技术标签:
【中文标题】如何在 iOS 中检测外部麦克风?【英文标题】:How can I detect external microphone in iOS? 【发布时间】:2015-10-26 10:58:09 【问题描述】:如何从我的应用程序中检测设备中是否插入了外部麦克风?
【问题讨论】:
【参考方案1】:试试这个:
let route = AVAudiosession.sharedInstance().currentRoute
for port in route.outputs
if port.portType == AVAudioSessionPortHeadphones
// Headphones located
编辑:发布有问题的 OP 更改 -
当应用程序运行时,您需要注册AVAudioSessionRouteChangeNotification
以收听如下更改:
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
【讨论】:
如何在应用程序运行时检测设备中是否插入了麦克风?我的意思是我希望每次插入麦克风时都能看到即时通知。 总是乐于提供帮助:-)!干杯!【参考方案2】: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
【讨论】:
【参考方案3】:使用 swift 2.0,此代码有效
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;
【讨论】:
【参考方案4】:使用AVAudioSession
,您可以列出availableInputs
let session = AVAudioSession.sharedInstance()
_ = try? session.setCategory(AVAudioSessionCategoryRecord, withOptions: [])
print(AVAudioSession.sharedInstance().availableInputs)
它返回一个AVAudioSessionPortDescription
的数组。您可以使用 portType“有线或内置”麦克风类型。
PS : 只能在真机上运行,不能在模拟器上运行。
【讨论】:
以上是关于如何在 iOS 中检测外部麦克风?的主要内容,如果未能解决你的问题,请参考以下文章