AVAudioSession和AirPods

时间:2017-12-14 15:21:13

标签: ios swift audio avfoundation avaudiosession

我的应用似乎与AirPods无法合作。现在我正在使用此代码进行播放和录制:

    let audioSession = AVAudioSession.sharedInstance()
    do { try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.defaultToSpeaker)
    }catch {
        print("audioSession properties weren't set because of an error.")
    }

如果我将defaultToSpeaker更改为allowBluetooth

是否足够?

P.S。我知道这是一个非常愚蠢的问题,因为更改这一行并检查更简单,但我现在没有AirPods,所以我唯一的选择就是将新版本上传到Testflight(和我希望用最少的迭代来做到这一点。)

更新(非常天真的方法 - 但我只需要使用蓝牙耳机):

func selectDevice(audioSession: AVAudioSession) {

    var headphonesExist = false
    var bluetoothExist = false
    var speakerExist = false

    let currentRoute = AVAudioSession.sharedInstance().currentRoute

    for output in audioSession.currentRoute.outputs {
        print(output)

        if output.portType == AVAudioSessionPortHeadphones || output.portType == AVAudioSessionPortHeadsetMic {
            headphonesExist = true
        }

        if output.portType == AVAudioSessionPortBluetoothA2DP || output.portType == AVAudioSessionPortBluetoothHFP {
            bluetoothExist = true
        }

        if output.portType == AVAudioSessionPortBuiltInSpeaker {
            speakerExist = true
        }
    }

    if bluetoothExist == true {
        do { try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.allowBluetooth) } catch {
            print("error with audiosession: bluetooth")
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您需要像这样向您的options参数添加对蓝牙的支持:

[AVAudioSessionCategoryOptions.defaultToSpeaker, .allowBluetoothA2DP]

.allowBluetoothA2DP将允许向蓝牙设备输出高质量的音频,并限制该设备上的麦克风输入,而.allowBluetooth将默认将HFP兼容(输入/输出)蓝牙设备设置为较低质量的HFP,支持麦克风输入。

答案 1 :(得分:0)

此处是请求适当权限的完整资料。 您要做的就是添加一个带有'.allowBluetoothA2DP'的模式

我已在Swift 5上应用

func requestPermissionForAudioRecording(){
    recordingSession = AVAudioSession.sharedInstance()
    
    do {
      // only with this without options, will not capable with your Airpod, the Bluetooth device.
      //  try recordingSession.setCategory(.playAndRecord, mode: .default)
      try recordingSession.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowAirPlay, .allowBluetoothA2DP])
      try recordingSession.setActive(true)
      recordingSession.requestRecordPermission() { allowed in
        DispatchQueue.main.async {
          if allowed {
            // Recording permission has been allowed
            self.recordingPermissionGranted = true
          } else {
            // failed to record!
          }
        }
      }
    } catch let err {
      // failed to record!
      print("AudioSession couldn't be set!", err)
    }
  }