我在我的应用程序中成功实现了 WebRTC,但是我遇到了一个问题,即音频会从接收器而不是接收器 + 扬声器发出。我最终修改了一个解决方案,我发现它可以在插入和拔出蓝牙耳机或普通耳机时处理音频路由。当我通过 WebRTC 库接收到音频时,通知通常会立即触发。
NotificationCenter.default.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: nil, using: routeChange)
func routeChange(_ n: Notification) {
guard let info = n.userInfo,
let value = info[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue: value) else { return }
switch reason {
case .categoryChange:
for description in AVAudioSession.sharedInstance().currentRoute.outputs {
if description.portType == AVAudioSession.Port.builtInSpeaker || description.portType == AVAudioSession.Port.builtInReceiver {
try? AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)
}
}
case .oldDeviceUnavailable:
try? AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)
default:
return
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当用户点击我的应用程序中的按钮时,此解决方案阻止我播放用作提示/反馈的音频文件。基本上,以下代码将播放音频文件,但它会以各种方式弄乱我上面的配置。它将主要使音频从接收器而不是扬声器和接收器出来。我相信它也与耳机有关。
private func playTapSound() {
guard let url = Bundle.main.url(forResource: App.AudioFile.tapFeedback, withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = audioPlayer else { return }
player.play()
} catch let error {
print("### Error - playing tap audio -", error.localizedDescription)
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在不影响 routeChange 方法的情况下播放音频文件。
| 归档时间: |
|
| 查看次数: |
771 次 |
| 最近记录: |