如何在iOS设备上检测耳机(扬声器)的可用性? [英] How to detect ear piece (speaker) availability on iOS devices?

查看:1605
本文介绍了如何在iOS设备上检测耳机(扬声器)的可用性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iPad上专门检测是否有可用的耳机。

I want to detect specially on iPad's if there is ear piece available or not.

例如 - 我可以检测iOS设备是否有使用AVFound的天赋是否有任何方法可以检测耳机的可用性。

For example - I can detect if the iOS device hasTourch or not using AVFoundation so is there any way to detect ear piece availability.

推荐答案

1)如果你想检查是否有耳机(接收器)扬声器)在设备上可用

您可以通过简单识别设备是否为iPhone来识别此信息。

You can identify this by simply identifying if Device is iPhone.

UIDevice.current.userInterfaceIdiom == .phone

UIDevice.current.userInterfaceIdiom == .phone

iOS prottype AVAudioSessionPortBuiltInReceiver 是否适用于builtInreceriver扬声器。
并根据 apple的文档,这仅适用于iPhone设备。因此,没有必要检查其他任何东西,如果它的iPhone,你有耳机片,如果它不是iPhone(在ipad上)它没有耳机。

in iOS prottype AVAudioSessionPortBuiltInReceiver is there for builtInreceriver speaker. and according to apple's documentation, This is available only on iPhone device. So there is no need to check for anything else, If its iPhone, You have Ear piece and if its not iPhone (on ipad) it don't have ear piece.

2)如果你想检查是否连接了手机:

您可以使用共享音频会话的电流来检查耳机是否已连接:
这里是 swift 3.0中的示例功能

You can use currentroute of share audio session to check if headset is connected or not: here is sample function in 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;
    } 

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

You should also monitor its status by listening for route change:

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

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

here is sample code for handler of notification setup above:

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设备上检测耳机(扬声器)的可用性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆