iOS how to discover bluetooth headset and its events

夙愿已清 提交于 2019-11-29 18:10:54
Ben

Like mentioned CoreBluetooth is for LE devices only,
so this is what I did to get the events for BluetoothHFP devices:
1. you need to open AVAudioSeesion:
link AVFoundation.framework to your project
2. for current available inputs:

NSArray *availInputs = [[AVAudioSession sharedInstance] availableInputs];

3. for notification on route change:
a. setup new AVAudioSession
b. register observer to AVAudioSessionRouteChangeNotification

- (BOOL)prepareAudioSession {

    // deactivate session
    BOOL success = [[AVAudioSession sharedInstance] setActive:NO error: nil];
    if (!success) {
        NSLog(@"deactivationError");
    }

    // set audio session category AVAudioSessionCategoryPlayAndRecord options AVAudioSessionCategoryOptionAllowBluetooth
    success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil];
    if (!success) {
        NSLog(@"setCategoryError");
    }

    // activate audio session
    success = [[AVAudioSession sharedInstance] setActive:YES error: nil];
    if (!success) {
        NSLog(@"activationError");
    }

    return success;
}

and call this when you want to start listen to changes:

[self prepareAudioSession];

NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self
                  selector:@selector(bluetoothAvailabilityDidChange:)
                      name:@"BluetoothConnectabilityChangedNotification"
                    object:nil];
  1. if you want to get the callbacks while on background, you need to add Audio and AirPlay on target's capabilities:

!! This answer was helpful to me when got the solution

CoreBluetooth.framework is for Bluetooth Low-Energy.
Bluetooth Low-Energy is not designed for passing sound (exit headset, speakers, etc.)
So my question is: Are your sure your headset is using Bluetooth Low-Energy?
I don't think so.

So, that's why the delegate method centralManager:didDiscoverPeripheral: isn't triggered.

If you want to get some events of the headset, like "user pressed next song", you can use the Remote Control Events. As I suspect you may want to listen to "others events", I guess your headset is under MFI. So it may have its own protocol. For example, I worked on the iOS app for a Bluetooth HeadSet that had others functionalities, like calling a favorite number, etc. But, then, you'll need to use ExternalAccessory.framework, and may have to reverse engineer the protocol.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!