我正在使用AVAudioSession來偵聽語音輸入。它適用於有線耳機,但它不適用於連接的藍牙設備。以下是我使用的設置輸入藍牙話筒代碼AVAudioSession不識別來自藍牙設備的音頻
func setupSessionForRecording() { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.allowBluetooth]) } catch let error as NSError { debugPrint("Error in listening "+error.localizedDescription) } var inputsPriority: [(type: String, input: AVAudioSessionPortDescription?)] = [ (AVAudioSessionPortLineIn, nil), (AVAudioSessionPortHeadsetMic, nil), (AVAudioSessionPortBluetoothHFP, nil), (AVAudioSessionPortUSBAudio, nil), (AVAudioSessionPortCarAudio, nil), (AVAudioSessionPortBuiltInMic, nil), ] for availableInput in audioSession.availableInputs! { guard let index = inputsPriority.index(where: { $0.type == availableInput.portType }) else { continue } inputsPriority[index].input = availableInput } guard let input = inputsPriority.filter({ $0.input != nil }).first?.input else { fatalError("No Available Ports For Recording") } do { try audioSession.setPreferredInput(input) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) try audioSession.setPreferredIOBufferDuration(10) } catch { fatalError("Error Setting Up Audio Session") } }
此代碼將停止服用從設備麥克風輸入和我也得到聲音在藍牙耳機,它已準備好傾聽,但它不」從設備中選擇任何輸入。
此外,
當我嘗試播放任何音頻到藍牙耳機它不工作。下面是代碼播放音頻
do { let output = AVAudioSession.sharedInstance().currentRoute.outputs[0].portType if output == "Receiver" || output == "Speaker"{ try AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker) } else{ try AVAudioSession.sharedInstance().overrideOutputAudioPort(.none) } print("Voice Out \(output)") } catch let error as NSError { print("audioSession error: \(error.localizedDescription)") os_log("Error during changing the current audio route: %@" , log: PollyVoiceViewController.log, type: .error, error) } catch { os_log("Unknown error during changing the current audio route", log: PollyVoiceViewController.log, type: .error) } do { let soundData = try Data(contentsOf: url as URL) self.audioPlayer = try AVAudioPlayer(data: soundData) self.audioPlayer?.prepareToPlay() self.audioPlayer?.volume = 3.0 self.audioPlayer?.delegate = self self.audioPlayer?.play() } catch let error as NSError { print("Error getting the audio file"+error.description) }
嗨,你解決了嗎? –