Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 787
Georg Avatar asked Jul 26 '17 14:07

Georg


2 Answers

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...)

like image 130
Georg Avatar answered Oct 21 '22 13:10

Georg


For swift 3, import AVKit then add

try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
like image 3
Jayprakash Singh Avatar answered Oct 21 '22 15:10

Jayprakash Singh