Use AVSpeechSynthesizer in background without stopping f.e. music app

Viewed 2911

I'd like to know how to properly let my iPhone speak one sentence while my app is in background but then return to whatever was playing before.

My question is quite similar to AVSpeechSynthesizer in background mode but again with the difference that I want to be able to "say something" while in background without having to stop Music that is playing. So while my AVSpeechSynthesizer is speaking, music should pause (or be a bit less loud) but then it should resume. Even when my app is currently in background.

What I am trying to archive is a spoken summary of tracking-stats while GPS-Tracking in my fitness app. And chances are that you are listening to music is quite high, and I don't want to disturb the user...

5 Answers

for swift 4.2 / Xcode 10

unfortunately .duckOthers is no longer available; I managed to make it work like that:

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

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)

Background music don't stop and your word sound play even phone in silent mode by this two line of code before usual text to speech codes :

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