AVAudioSession DefaultToSpeaker仍在播放来自接收器的音频

问题描述

我有一个允许用户在录制视频的同时播放音频的应用程序。他们只能在风景中记录。

这是我在视频会话期间设置音频播放的方式:

         guard allowBackgroundAudio == true else {
             return
         }
 
         guard audioEnabled == true else {
             return
         }
 
         do{
             if #available(iOS 10.0,*) {
                 try AVAudioSession.sharedInstance().setCategory(.playAndRecord,mode: .default,options: [.mixWithOthers,.defaultToSpeaker])
             } else {
                 let options: [AVAudioSession.CategoryOptions] = [.mixWithOthers,.allowBluetooth]
                               let category = AVAudioSession.Category.playAndRecord
                 let selector = NSSelectorFromString("setCategory:withOptions:error:")
                 AVAudioSession.sharedInstance().perform(selector,with: category,with: options)
             }
             try AVAudioSession.sharedInstance().setActive(true)
             session.automaticallyConfiguresApplicationAudioSession = false
         }
         catch {
             print("[SwiftyCam]: Failed to set background audio preference")
 
         }
     }

问题在于音频仍在从接收器中略微播放,这意味着顶级麦克风正在接听音频播放,淹没了用户的音频。

在这里阅读到仍在播放的接收扬声器可能是Apple的一个错误(或功能)后,我决定将后置麦克风用于自拍相机,从而将音频从麦克风中分离出来。我似乎无法让自拍相机使用后置麦克风。

   public class func setMicrophone(_ uiorient: String) {

        guard let inputs = AVAudioSession.sharedInstance().availableInputs else {
            return
        }

        for input in inputs {
            print(input.dataSources ?? "??")
        }

        // set preferred:
        let preferredPort = inputs[0]
        if let dataSources = preferredPort.dataSources {
            for source in dataSources {
                if source.dataSourceName == uiorient {
                    do {
                        try preferredPort.setPreferredDataSource(source)
                    }
                    catch _ {
                        print("Cannot set \(uiorient) microphone.")
                    }
                }
            }
        }
    }

然后在调用自拍相机时使用它;

AudioRecorderViewController.setMicrophone("Back")

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)