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

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)

For swift 3, import AVKit then add

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

I found the answer myself...

The important part ist to configure the AVAudioSession with the .duckOthers option:

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

This will make playback of f.e. music less loud but this would make it stay less loud even when speech is done. This is why you need to set a delegate for the AVSpeechSynthesizer and then handle it like so:

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

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

That way, music will continue with normal volume after speech is done.

Also, right before speaking, I activate my audioSession just to make sure (not sure if that would really be necessary, but since I do so, I have no more problems...)