1. Bluetooth audio protocols are commonly divided into two types:
1. One-way high-fidelity audio protocol (ie: output), its common type is BluetoothA2DPOutput, mainly for listening to music and watching videos;
2. Bidirectional low-fidelity audio protocol (ie: output, input), the common types are BluetoothHFP (ie: Hands-Free Profile) and BluetoothHSP (HeadSet Profile), both listening and speaking;
2. Get status
1. Bluetooth is turned on and the headset is not connected - Speaker
2. One-way high-definition audio protocol (output) - BluetoothA2DPOutput
3. Bidirectional low-fidelity audio protocol (output, input) - BluetoothHFP, BluetoothHSP
3. Method implementation
Get connection status
#pragma mark - ****************************** 蓝牙耳机是否链接 - 状态
+ (BOOL)isBluetoothHeadsetConnectedState {
AVAudioSession *session = [AVAudioSession sharedInstance];
AVAudioSessionRouteDescription *routeDescription = [session currentRoute];
if (routeDescription) {
NSArray *outputs = [routeDescription outputs];
if (outputs && 0 < [outputs count]) {
AVAudioSessionPortDescription *portDescription = [outputs objectAtIndex:0];
NSString *portType = [portDescription portType];
if (portType && [portType isEqualToString:@"BluetoothA2DPOutput"] && [portType isEqualToString:@"BluetoothHFP"] && [portType isEqualToString:@"BluetoothHSP"]) {
return YES;
}
}
}
return NO;
}
2. Get the connection entity
#pragma mark - ****************************** 蓝牙耳机是否链接 - 实体
+ (AVAudioSessionPortDescription *)isBluetoothHeadsetConnectedEntity {
/*
蓝牙开启未链接耳机:
Speaker
单向保真音频协议(输出):
BluetoothA2DPOutput
...
双向保真音频协议(输入 & 输入):
BluetoothHFP - HFP(Hands-Free Profile)
BluetoothHSP - HSP(HeadSet Profile)
其它:
Receiver
*/
AVAudioSession *session = [AVAudioSession sharedInstance];
AVAudioSessionRouteDescription *routeDescription = [session currentRoute];
// NSLog(@"%@", routeDescription);
if (routeDescription) {
NSArray *outputs = [routeDescription outputs]; // 输入源
if (outputs && 0 < [outputs count]) {
AVAudioSessionPortDescription *portDescription = [outputs objectAtIndex:0];
NSString *portType = [portDescription portType];
NSLog(@"PortType: %@", portType); // 蓝牙开启未链接: Speaker && 链接耳机: BluetoothA2DPOutput BluetoothHFP BluetoothHSP
if (portType && [portType isEqualToString:@"BluetoothA2DPOutput"]) {
NSLog(@"[蓝牙检测] - 状态 - 输出 - %@", [portDescription portName]);
return portDescription;
} else if (portType && [portType isEqualToString:@"BluetoothHFP"] && [portType isEqualToString:@"BluetoothHSP"]) {
NSLog(@"[蓝牙检测] - 状态 - 输出 & 输入 - %@", [portDescription portName]);
return portDescription;
}
}
}
return nil;
}
CoreBluetooth Bluetooth switching status real-time detection
The above is all the content shared this time, I hope it can be helpful to everyone!