I want to use Google's Text-To-Speech API in an Android app but I only could find the way to do it from web (Chrome). This is my first attempt to play "Hello world" from the app.
playTTS
is the onClick and it is been executed, but no sound is played. Is there any JS/Java library I need to import? Is it possible to generate an audio file from it?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBrowser = new WebView(this);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void playTTS(View view) {
myBrowser.loadUrl("javascript:speechSynthesis.speak(
SpeechSynthesisUtterance('Hello World'))");
}
Code for TTS:
In Android java code your Activity/other Class should implement
TextToSpeech.OnInitListener
. You will get aTextToSpeech
instance by callingTextToSpeech(context, this)
. (Wherecontext
refers to your application's Context -- can bethis
in an Activity.) You will then receive aonInit()
callback withstatus
which tells whether the TTS engine is available or not.You can talk by calling
tts.speak(textToBeSpoken, TextToSpeech.QUEUE_FLUSH, null)
ortts.speak(textToBeSpoken, TextToSpeech.QUEUE_ADD, null)
. The first one will interrupt any "utterance" that is still being spoken and the latter one will add the new "utterance" to a queue. The last parameter is not mandatory. It could be an "utterance id" defined by you in case you want to monitor the TTS status by setting anUtteranceProgressListener
. (Not necessary)In Java code a simple "TTS talker" class could be something like: