【问题标题】:Using the iPhone speakers with AVSpeechSynthesizer使用带有 AVSpeechSynthesizer 的 iPhone 扬声器
【发布时间】:2020-05-16 17:14:43
【问题描述】:

我正在使用以下代码在我的 iOS 应用中添加文本到语音功能:

try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker)
try! AVAudioSession.sharedInstance().setActive(true)
try! AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)

let speech : String = "You have the following items in your To-do list: "
let speechUtterance : AVSpeechUtterance = AVSpeechUtterance(string: speech)
AVSpeechSynthesizer().speakUtterance(speechUtterance)

代码运行良好,但声音来自手机的麦克风。我想使用扬声器而不是麦克风。我如何做到这一点?

【问题讨论】:

  • try!”是有效的 Swift 语法吗?
  • 我认为您对覆盖的理解是从后到前的 - 您是否尝试过 .None 而不是 .Speaker? .

标签: ios swift avspeechsynthesizer


【解决方案1】:

我使用 SFSpeechRecognizer 进行语音识别,之后为了向说话者播放话语,您必须执行以下操作。

  let audioSession = AVAudioSession.sharedInstance()  
     do {

    try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
    try audioSession.setMode(AVAudioSessionModeSpokenAudio)
    try audioSession.setActive(true, with: .notifyOthersOnDeactivation)

                    let currentRoute = AVAudioSession.sharedInstance().currentRoute
                        for description in currentRoute.outputs {
                            if description.portType == AVAudioSessionPortHeadphones {
                                 try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.none)
                                print("headphone plugged in")
                            } else {
                                print("headphone pulled out")
                                 try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
                            }
                    }

} catch {
      print("audioSession properties weren't set because of an error.")
}

【讨论】:

  • 你的意思是说之前,而不是之后?我的意思是你必须在 tts 说话之前而不是之后设置音频会话
  • 是在应用播放声音之前。我在播放声音之前有语音识别(音频会话有不同的设置),所以我需要在播放声音之前更改音频会话。
猜你喜欢
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多