Add Text-to-Speech support for your app
--
In this post, we shall continue adding features to the app we created in this post. In the mentioned post, we used Firebase ML Kit to recognize text from images taken from our camera. What we will do next is read the text displayed on the TextView out aloud by adding text-to-speech support.
Layout
Let’s start by adding a Seekbar and a button. The Seekbar handles the talking speed and the button triggers the text-to-speech functionality to read the text displayed out aloud. Right below the TextView with id txt_image
add the following lines of code:
Adding text-to-speech functionality
Next, we need to bind our elements by id in the onCreate
method. We shall also declare a TextToSpeech
object that is provided by Android. Name that object mTextToSpeech
. Afterwards, we need to create an object of the TextToSpeech
class. Here, we shall set our preferred locale which in this case is Locale.US
as my preferred language.
We then need to add an onClickListener
to our button as well. We need to check for the text recognized in the TextView and if it is null, a Toast message will be shown. You can also slide the Seekbar to control the talking speed. Finally, we add an onDestroy
method so as to stop the text-to-speech as soon as it completes and not keep repeating.
You can find the repository on GitHub here: