如何在iOS中检测外部麦克风?

时间:2015-10-26 10:58:09

标签: ios swift audio

如何在我的应用程序中检测设备中是否插有外部麦克风?

4 个答案:

答案 0 :(得分:4)

试试这个:

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
    }
}

答案 1 :(得分:1)

<强> 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
    }
}

答案 2 :(得分:0)

使用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;
    }
}

答案 3 :(得分:0)

使用AVAudioSession,您可以列出availableInputs

    let session = AVAudioSession.sharedInstance()

    _ = try? session.setCategory(AVAudioSessionCategoryRecord, withOptions: [])

    print(AVAudioSession.sharedInstance().availableInputs)

返回AVAudioSessionPortDescription数组。你可以使用portType&#34;有线或内置&#34;麦克风类型。

PS:它只适用于不在模拟器上的真实设备。