gpt4 book ai didi

ios - 如何检测 iOS 设备上的耳机(扬声器)可用性?

转载 作者:搜寻专家 更新时间:2023-11-01 06:04:30 49 4
gpt4 key购买 nike

我想在iPad上专门检测一下有没有耳机

例如 - 我可以使用 AVFoundation 检测 iOS 设备是否有 Tourch,所以有什么方法可以检测耳机的可用性。

最佳答案

1) 如果你想检查设备上是否有听筒(Receiver speaker)

您可以通过简单地识别设备是否为 iPhone 来识别这一点。

UIDevice.current.userInterfaceIdiom == .phone

在 iOS prottype AVAudioSessionPortBuiltInReceiver 中有 builtInreceriver 扬声器。并根据 apple's documentation , 这仅适用于 iPhone 设备。因此,无需检查其他任何东西,如果是 iPhone,则您有耳机,如果不是 iPhone(在 ipad 上),则没有耳机。

2)如果要检查耳机是否连接:

您可以使用共享 Audio Session 的当前路径来检查耳机是否已连接:这是 swift 3.0

中的示例函数
   func IsHeadSetConnected() -> Bool{
let route = AVAudioSession.sharedInstance().currentRoute;
for desc in route.outputs
{
let portType = desc.portType;
if (portType == AVAudioSessionPortHeadphones)
{
return true;
}

}

return false;
}

您还应该通过监听路由变化来监控其状态:

NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange(_:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil)

这是上面通知设置处理程序的示例代码:

func handleRouteChange(_ notification: Notification) {
guard
let userInfo = notification.userInfo,
let reasonRaw = userInfo[AVAudioSessionRouteChangeReasonKey] as? NSNumber,
let reason = AVAudioSessionRouteChangeReason(rawValue: reasonRaw.uintValue)
else { fatalError("Strange... could not get routeChange") }
switch reason {
case .oldDeviceUnavailable:
print("oldDeviceUnavailable")
case .newDeviceAvailable:
print("headset/line plugged in")
case .routeConfigurationChange:
print("headset pulled out")
case .categoryChange:
print("Just category change")
default:
print("not handling reason")
}
}

关于ios - 如何检测 iOS 设备上的耳机(扬声器)可用性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41374565/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com