Text To Speech (TTS) iOS7

2k Views Asked by At

My application wants to play some text when it is available, and if there is some music playing in the background I want to lower the voice for the music while my app is playing its text, what I did is:

[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                 withOptions:AVAudioSessionCategoryOptionDuckOthers
                                      error:&err];
[[AVAudioSession sharedInstance] setActive:YES error:&err];

The option AVAudioSessionCategoryOptionDuckOthers will lower the music volume while my app is playing its text. Then play the text with the speechSynthesizer, after that in:

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)

utterance I do:

[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];

so the music will be back to it original volume.

The problem by setting the session active to NO, I am loosing the volume control (the iPhone hardware volume control the one in the left side of the phone). i.e I can not upper or lower the volume for my app unless there is a text actively playing in my app at the moment I am changing the volume.

2

There are 2 best solutions below

9
matt On

Immediately after setting setActive: to NO, set it to YES again! Set the category to Ambient so the background sound can continue playing.

So, before you play:

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient
                                 withOptions: AVAudioSessionCategoryOptionDuckOthers
                                       error: nil];
[[AVAudioSession sharedInstance] setActive:YES withOptions: 0 error:nil];

After you play:

[[AVAudioSession sharedInstance] setActive:NO withOptions:0 error:nil];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient
                                 withOptions: 0
                                       error: nil];
[[AVAudioSession sharedInstance] setActive:YES withOptions: 0 error:nil];
0
user3456603 On

Thank you very much, It works if I did this, before I play my text:

[[AVAudioSession sharedInstance] setActive:NO withOptions:0 error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                 withOptions:AVAudioSessionCategoryOptionDuckOthers
                                       error:nil];

I had to setActive:NO as without it the second time when I play my text the music will be paused!!

And then After I play my text, I do this:

[[AVAudioSession sharedInstance] setActive:NO withOptions:0 error:nil];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient withOptions: 0 error: nil];
[[AVAudioSession sharedInstance] setActive:YES withOptions: 0 error:nil];