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

标签 ios swift avfoundation avaudiosession

我想在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/

相关文章:

ios - 解析查询结果未添加(附加)到 iOS Swift 中的本地数组

ios - Swift 4 AVFoundation - 同时录制多个音频源

macos - 使用 AVFoundation (OSX) 向视频添加过滤器 - 如何将生成的图像写回 AVWriter?

ios - CFBundleDisplayName 中的空间与 plutil

ios - 应用未加载

ios - 在 iOS 上以编程方式控制通知 "Show Previews"选项

ios - 以编程方式向已以编程方式添加到表格单元格的标签添加约束

Swift Google map - 加载区域设置图 block

ios - 如何更新 StoryBoard 中的 NSLayoutConstraint?

swift - 我的相机应用程序 Swift 代码中有几个错误