美文网首页iOS工具收藏
iOS设置蓝牙外设播放音频

iOS设置蓝牙外设播放音频

作者: 8ef7f923f5bb | 来源:发表于2022-03-02 19:24 被阅读0次

    首先,你需要明确地通知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];
    }

    相关文章

      网友评论

        本文标题:iOS设置蓝牙外设播放音频

        本文链接:https://www.haomeiwen.com/subject/apderrtx.html