如何确定外接耳机是否连接到iPhone?

问题描述 投票:3回答:3

是否可以检测到用户的外部耳机已插入iPhone的3.5毫米连接器或30针连接器?我想只将音频输出到外部音频设备,如果没有连接,请保持静音。

iphone objective-c core-audio
3个回答
2
投票

答案非常类似于this question的答案,但你会想要获得kAudioSessionProperty_AudioRoute属性。


2
投票

调用此方法可以找出蓝牙耳机是否已连接。

首先导入这个框架#import <AVFoundation/AVFoundation.h>

- (BOOL) isBluetoothHeadsetConnected
    {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        AVAudioSessionRouteDescription *routeDescription = [session currentRoute];

        NSLog(@"Current Routes : %@", routeDescription);

        if (routeDescription)
        {
            NSArray *outputs = [routeDescription outputs];

            if (outputs && [outputs count] > 0)
            {
                AVAudioSessionPortDescription *portDescription = [outputs objectAtIndex:0];
                NSString *portType = [portDescription portType];

                NSLog(@"dataSourceName : %@", portType);

                if (portType && [portType isEqualToString:@"BluetoothA2DPOutput"])
                {
                    return YES;
                }
            }
        }

        return NO;
    }

0
投票

在Apple文档中有关于此的很好的文章:https://developer.apple.com/documentation/avfoundation/avaudiosession/responding_to_audio_session_route_changes

只有你必须验证portType == AVAudioSessionPortBluetoothA2DP

func setupNotifications() {
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self,
                               selector: #selector(handleRouteChange),
                               name: .AVAudioSessionRouteChange,
                               object: nil)
}


@objc func handleRouteChange(notification: Notification) {
    guard let userInfo = notification.userInfo,
        let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
        let reason = AVAudioSessionRouteChangeReason(rawValue:reasonValue) else {
            return
    }
    switch reason {
    case .newDeviceAvailable:
        let session = AVAudioSession.sharedInstance()
        for output in session.currentRoute.outputs where output.portType == AVAudioSessionPortBluetoothA2DP {
            headsetConnected = true
            break
        }
    case .oldDeviceUnavailable:
        if let previousRoute =
            userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
            for output in previousRoute.outputs where output.portType == AVAudioSessionPortBluetoothA2DP {
                headsetConnected = false
                break
            }
        }
    default: ()
    }
}

func isBluetoothHeadsetConnected() -> Bool {
    var result = false
    let session = AVAudioSession.sharedInstance()
    for output in session.currentRoute.outputs where output.portType == AVAudioSessionPortBluetoothA2DP {
        result = true
    }
    return result
}
© www.soinside.com 2019 - 2024. All rights reserved.