简体   繁体   English

如何检测 iOS 中是否连接了 HFP 或 A2DP?

[英]How can I detect whether an HFP or A2DP is connected in iOS?

I am working on a project which can play music via HFP device.我正在开发一个可以通过 HFP 设备播放音乐的项目。 But here's a problem that I want to detect whether an HFP or A2DP is connected when music is playing.但这里有一个问题,我想检测播放音乐时是否连接了 HFP 或 A2DP。

Now I am using the AVFoundation framework to do this.现在我使用 AVFoundation 框架来做到这一点。 Here's the code:这是代码:

- (BOOL)isConnectedToBluetoothPeripheral
{
    BOOL isMatch = NO;
    NSString* categoryString = [AVAudioSession sharedInstance].category;
    AVAudioSessionCategoryOptions categoryOptions = [AVAudioSession sharedInstance].categoryOptions;
    if ((![categoryString isEqualToString:AVAudioSessionCategoryPlayAndRecord] &&
         ![categoryString isEqualToString:AVAudioSessionCategoryRecord]) ||
        categoryOptions != AVAudioSessionCategoryOptionAllowBluetooth)
    {
        NSError * error = nil;
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
                                         withOptions:AVAudioSessionCategoryOptionAllowBluetooth
                                               error:&error];
        if (error) {
            [[AVAudioSession sharedInstance] setCategory:categoryString
                                             withOptions:categoryOptions
                                                   error:&error];
            return isMatch;
        }
    }
    
        NSArray * availableInputs = [AVAudioSession sharedInstance].availableInputs;
        for (AVAudioSessionPortDescription *desc in availableInputs)
        {
            if ([[desc portType] isEqualToString:AVAudioSessionPortBluetoothA2DP] || [[desc portType] isEqualToString:AVAudioSessionPortBluetoothHFP])
            {
                    isMatch = YES;
                    break;
            }
        }
        if (!isMatch)
        {
            NSArray * outputs = [[[AVAudioSession sharedInstance] currentRoute] outputs];
            
            for (AVAudioSessionPortDescription * desc in outputs)
            {
                if ([[desc portType] isEqualToString:AVAudioSessionPortBluetoothA2DP] || [[desc portType] isEqualToString:AVAudioSessionPortBluetoothHFP])
                {
                        isMatch = YES;
                        break;
                }
            }
        }
        
        NSError * error = nil;
        [[AVAudioSession sharedInstance] setCategory:categoryString
                                         withOptions:categoryOptions
                                               error:&error];
    
        return isMatch;
}

It works well but cause another problem: when music is playing, using this method to detect HFP connection will make music playing interrupt for about two seconds.它运行良好,但会导致另一个问题:在播放音乐时,使用此方法检测 HFP 连接会导致音乐播放中断约 2 秒。

So I tried another way which can reduce the effect of detecting HFP connecting.所以我尝试了另一种可以降低检测HFP连接效果的方法。 I am using a flag我正在使用旗帜

static BOOL isHFPConnectedFlag

To indicate whether HFP or A2DP is connected.指示连接的是 HFP 还是 A2DP。 I use previous method to detect the connection only once (when the app is launching) and save the result into isHFPConnectedFlag.我使用以前的方法只检测一次连接(当应用程序启动时)并将结果保存到 isHFPConnectedFlag 中。 What's more, I observe the AudioSessionRouteChange to sync the connection status:更重要的是,我观察 AudioSessionRouteChange 以同步连接状态:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionRouteChangeWithState:) name:AVAudioSessionRouteChangeNotification object:nil];

When the route change reason is AVAudioSessionRouteChangeReasonNewDeviceAvailable or AVAudioSessionRouteChangeReasonOldDeviceUnavailable I can know HFP is connected or disconnected.当路由更改原因是AVAudioSessionRouteChangeReasonNewDeviceAvailableAVAudioSessionRouteChangeReasonOldDeviceUnavailable我可以知道 HFP 已连接或断开连接。 Unfortunately, when I connect some HFP in my iPhone, the system will not post this notification, so I cannot detect the connection in this situation.不幸的是,当我在 iPhone 中连接某些 HFP 时,系统不会发布此通知,因此在这种情况下我无法检测到连接。

Does anyone know the reason or a better way to implements this (Detecting HFP connection without music playing interrupting)?有谁知道实现此目的的原因或更好的方法(在不中断音乐播放的情况下检测 HFP 连接)?

you can use like this!你可以这样使用!

    -(BOOL) bluetoothDeviceA2DPAvailable {

    BOOL available = NO;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    AVAudioSessionRouteDescription *currentRoute = [audioSession currentRoute];

    for (AVAudioSessionPortDescription *output in currentRoute.outputs) {
        if (([[output portType] isEqualToString:AVAudioSessionPortBluetoothA2DP] ||
             [[output portType] isEqualToString:AVAudioSessionPortBluetoothHFP])) {
            available = YES;
            break;
        }
    }
    return available;
}

Swift 5 version:斯威夫特 5版本:

func bluetoothDeviceHFPAvailable() -> Bool {
    let audioSession = AVAudioSession.sharedInstance()
    let currentRoute = audioSession.currentRoute

    for output in currentRoute.outputs {
        if output.portType == .bluetoothHFP || output.portType == .bluetoothA2DP {
            return true
        }
    }

    return false
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 iOS蓝牙双模; 同时将BLE(GATT)连接到已连接的BR / EDR(A2DP / HFP)立体声耳机 - iOS Bluetooth dual-mode; connect BLE (GATT) to an already connected BR/EDR (A2DP/HFP) stereo headset simultaneously 如何以编程方式扫描并连接到iOS上的Bluetooth A2DP设备 - How to scan and connect to Bluetooth A2DP device on iOS programmatically iOS上的蓝牙A2DP API支持? - Bluetooth A2DP API Support on iOS? 如何检测iOS设备是否处于静默模式? - How can I detect whether an iOS device is in silent mode or not? 我可以检测到 iOS 设备连接了外部 GPS 吗? - Can I detect that an iOS device has external GPS connected? 如何在iPhone上使用A2DP连接到远程设备 - How to connect to a remote device using A2DP on iPhone 如何使用蓝牙4.0(BLE)如何使A2DP蓝牙配置文件工作? 我需要AptX编解码器吗? - How are you able to get an A2DP bluetooth profile to work using bluetooth 4.0 (BLE)? Do I need an AptX codec? 如何可靠地检测是否在 iOS 9 上连接了外接键盘? - How to reliably detect if an external keyboard is connected on iOS 9? 如何检测两个CALayer是否重叠? - How can i detect whether two CALayers overlap? Flutter iOS:无法检测到已连接的 iOS 模拟器 - Flutter iOS: Can't detect connected iOS simulator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM