【问题标题】:Use AVSpeechSynthesizer in background without stopping f.e. music app在后台使用 AVSpeechSynthesizer 而无需停止 f.e.音乐应用
【发布时间】:2020-10-20 22:40:12
【问题描述】:

我想知道如何正确让我的 iPhone 在我的应用处于后台时说出一句话,然后返回到之前播放的内容。

我的问题与AVSpeechSynthesizer in background mode 非常相似,但不同之处在于我希望能够在后台而不停止正在播放的音乐时“说点什么”。所以当我的AVSpeechSynthesizer 说话时,音乐应该暂停(或者声音小一点),然后它应该恢复。即使我的应用当前处于后台。

我要存档的是我的健身应用程序中 GPS 跟踪时跟踪统计数据的口头摘要。而且你听音乐的可能性很大,我不想打扰用户......

【问题讨论】:

  • 您是否已经看过 AVAudioSessionCategoryOptionMixWithOthers 和类似选项?

标签: ios avspeechsynthesizer


【解决方案1】:

我自己找到了答案……

使用.duckOthers 选项配置AVAudioSession 的重要部分:

let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)

这将播放 f.e.音乐不那么响亮,但这会使它即使在演讲结束时也保持不那么响亮。这就是为什么您需要为AVSpeechSynthesizer 设置一个委托,然后像这样处理它:

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
    guard !synthesizer.isSpeaking else { return }

    let audioSession = AVAudioSession.sharedInstance()
    try? audioSession.setActive(false)
}

这样,演讲结束后音乐将以正常音量继续播放。

另外,在说话之前,我激活了我的 audioSession 只是为了确保(不确定这是否真的有必要,但既然我这样做了,我就没有更多问题了......)

【讨论】:

  • 使用这个:[.duckOthers, .interruptSpokenAudioAndMixWithOthers]。语音部分完成后,它将立即恢复(音乐应用等)的音量正常。
【解决方案2】:

对于 swift 3,导入 AVKit 然后添加

try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

【讨论】:

  • 您必须在 AppDelegate 中配置音频会话
  • 我已经找到了解决方案...我必须设置类别但还要将选项设置为.duckOthers。然后我需要AVSpeechSynthesizer 的代表,并在会话结束后将会话设置为不活动...
  • AVKit 必须替换为 AVFoundation 并在后台模式下设置“Audio and AirPlay”显然仍然需要
【解决方案3】:

适用于 Swift 4.2 / Xcode 10

不幸的是 .duckOthers 不再可用;我设法让它像这样工作:

    let audioSession = AVAudioSession.sharedInstance()
    try! audioSession.setCategory(AVAudioSession.Category.ambient, mode: .default)

【讨论】:

  • try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.duckOthers])
【解决方案4】:

Swift 5.0

let synthesizer = AVSpeechSynthesizer()
let synthesizerVoice = AVSpeechSynthesisVoice(language: "en-US")

let str = "String"
let utterance = AVSpeechUtterance(string: str)

let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setCategory(
    AVAudioSession.Category.playback,
    options: AVAudioSession.CategoryOptions.mixWithOthers
)
        
utterance.rate = 0.5
utterance.voice = synthesizerVoice

synthesizer.speak(utterance)

【讨论】:

  • 如果用户想要柔化背景音乐或声音,选项可以是“duckOthers”。
【解决方案5】:

通过这两行代码之前通常的文本到语音代码,背景音乐不会停止,您的单词声音甚至可以在静音模式下播放:

let audioSession = AVAudioSession.sharedInstance()
try!audioSession.setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多