I am making a caller speaking application which speak caller name using TTS. I want to pause the ringtone while TTS is speaking then resuming the ringtone. From what i have researched we can use AudioFocus
(hope so).
Anyway i am using the following code
Update
I am using this code now.
public void speak(final String talk) throws InterruptedException {
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int musicVolume= audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolume, 0);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
int result = tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
// TODO Auto-generated method stub
}
@Override
public void onError(String utteranceId) {
// TODO Auto-generated method stub
}
@Override
public void onDone(String utteranceId) {
// TODO Auto-generated method stub
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
System.out.println("done");
}
});
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId");
tts.speak(talk, TextToSpeech.QUEUE_FLUSH, params);
System.out.println("speaking after tts is over" + talk+" "+result);
}
Although the Ringtone
is stopped and tts
is played but after tts
is played Ringtone
is not resumed. What should i do?
Finally after scratching my head for two days i finally did it. For all those who want to implement something like this but are unable to do so here is the code
explaination :-
ringVolume
- gets the current volume of the ringtone .i.e ringtone volume set in the phone.musicVolume
- gets the current volume of the musiccurrentRingVolume
just retains theringVolume
.Note-
STREAM_RING
andSTREAM_MUSIC
are different things. SeeNow the basic idea is to
mute
theringtone
whileTTS
is speaking and then set it to previous value.seekBarValue
- is mySeekBar
which depicts the level of theTTS
volume w.r.tmusicVolume
and is optional.PauseRingtone
- is aCheckBox Preference
which checks whether we want to pause ringtone while speaking. Iftrue
is sets theAudioManager.STREAM_RING
to1
i.e.vibrate
elseringVolume
i.e.Phone Value
, so bothTTS
andRingtone
play at the same time.sets the volume of
TTS
tomusicVolume
. AfterTTS
has completed speaking i.e. inonDone()
we set the volume ofRingtone
back to theringVolume
usingcurrentRingVolume
.If my answer helped mark my answer useful.
Get rid of this focus listener and add this code phoneStateListener class. This will solve your problem.