首先,你需要明确地通知AVAudioSession你允许声音可以被输出到蓝牙设备,通过setCategory设置
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionAllowBluetoothA2DP
error:&error];
通过增加AVAudioSessionCategoryOptionAllowBluetoothA2DP, 我们允许iOS通过蓝牙音频设备来播放我们App的声音。
接下来是设置蓝牙设备作为音频播放
1.设置为蓝牙外设播放
NSArray * bluetoothRoutes = @[AVAudioSessionPortBluetoothA2DP, AVAudioSessionPortBluetoothLE,
AVAudioSessionPortBluetoothHFP];
NSArray * routes = [[AVAudioSession sharedInstance] availableInputs];
AVAudioSessionPortDescription blueRoute;
for (AVAudioSessionPortDescription route in bluetoothRoutes)
{
if ([types containsObject:route.portType])
{
blueRoute = route;
}
}
NSError *error;
if (blueRoute) {
BOOL changeResult = [[AVAudioSession sharedInstance] setPreferredInput:bluetoothPort
error:&audioError];
}
2.设置耳机
NSArray * headsetRoutes = @[AVAudioSessionPortBuiltInMic];
NSArray * routes = [[AVAudioSession sharedInstance] availableInputs];
AVAudioSessionPortDescription headsetRoute;
for (AVAudioSessionPortDescription route in headsetRoutes)
{
if ([types containsObject:route.portType])
{
headsetRoute = route;
}
}
NSError *error;
if (headsetRoute) {
BOOL changeResult = [[AVAudioSession sharedInstance] setPreferredInput:headsetRoute
error:&audioError];
}
3.设置麦克风
NSArray * speakerRoutes = @[AVAudioSessionPortBuiltInSpeaker];
AVAudioSessionPortBluetoothHFP];
NSArray * routes = [[AVAudioSession sharedInstance] availableInputs];
AVAudioSessionPortDescription speakerRoute;
for (AVAudioSessionPortDescription route in speakerRoutes)
{
if ([types containsObject:route.portType])
{
speakerRoute = route;
}
}
NSError *error;
if (speakerRoute) {
BOOL changeResult = [[AVAudioSession sharedInstance] setPreferredInput:speakerRoute
error:&audioError];
}
网友评论