iOS如何发现蓝牙耳机及其事件

时间:2014-05-21 07:11:43

标签: objective-c bluetooth bluetooth-lowenergy core-bluetooth ios-bluetooth

我正在尝试发现"蓝牙耳机"并得到它的事件。我阅读了" CoreBluetooth" 文档并实现了如下示例代码。它不会触发委托方法' didDiscoverPeripheral'。

有没有解决方案?

代码:

CBCentralManager *myCentralManager;
[myCentralManager scanForPeripheralsWithServices:nil options:nil];


-(void)centralManagerDidUpdateState:(CBCentralManager *)central{

    //following line prints CBCentralManagerStatePoweredOn

    NSLog(@"state:%@", [self getCentralManagerState:central.state]);
}


//following method does not fire

-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{

}

2 个答案:

答案 0 :(得分:2)

如前所述,CoreBluetooth仅适用于LE设备,
这就是我为获取BluetoothHFP 设备的事件所做的工作:
1.你需要打开AVAudioSeesion:
AVFoundation.framework链接到您的项目
2.对于当前可用的输入:

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

3。关于路线变更的通知:
一个。设置新AVAudioSession
湾将观察者注册到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;
}

并在您想要开始收听更改时调用此方法:

[self prepareAudioSession];

NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self
                  selector:@selector(bluetoothAvailabilityDidChange:)
                      name:@"BluetoothConnectabilityChangedNotification"
                    object:nil];
  1. 如果你想在后台获得回调,你需要在目标的能力上添加音频和AirPlay:
    enter image description here
  2. !!获得解决方案后,This回答对我很有帮助

答案 1 :(得分:1)

CoreBluetooth.framework适用于低功耗蓝牙 Bluetooth Low-Energy不适用于传递声音(退出耳机,扬声器等) 所以我的问题是:您确定您的耳机使用蓝牙低功耗吗? 我不这么认为。

那么,这就是为什么代理方法centralManager:didDiscoverPeripheral:没有被触发的原因。

如果您想要获取耳机的某些事件,例如"用户按下下一首歌曲",您可以使用Remote Control Events。 因为我怀疑你可能想听#34;其他事件",我想你的耳机是MFI。所以它可能有自己的协议。例如,我在iOS应用程序上处理了具有其他功能的蓝牙HeadSet,例如拨打喜欢的号码等等。但是,您需要使用ExternalAccessory.framework,并且可能需要进行逆向工程协议。