Xamarin / playing background music and pausing for sound / text to speech (tts) playback

In FinishedLaunching, add:

AVAudioSession.SharedInstance().SetCategory (AVAudioSessionCategory.Ambient);

This will make any background music/sounds continue to play when starting your app. 
When playing a sound / tts in the app, use; 
            

var avsession = AVAudioSession.SharedInstance();
avsession.SetActive (true);
avsession.SetCategory (AVAudioSessionCategory.Playback, AVAudioSessionCategoryOptions.DuckOthers);

This will lower the volume on the background music, now you can play the desired sound, for instance (in my current case it is tts); 

speaker.SpeakUtterance (speechUtterance);

Depending on what you are playing, it has a DidFinish, for instance; 

speaker.DidFinishSpeechUtterance += (object sender, AVSpeechSynthesizerUteranceEventArgs e) => {
avsession.SetActive (false, AVAudioSessionSetActiveOptions.NotifyOthersOnDeactivation);
};    

Which will tell the background music to ‘unduck’. 

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>