Text to speak android

Android — Text To Speech

Android allows you convert your text into voice. Not only you can convert it but it also allows you to speak text in variety of different languages.

Android provides TextToSpeech class for this purpose. In order to use this class, you need to instantiate an object of this class and also specify the initListener. Its syntax is given below −

In this listener, you have to specify the properties for TextToSpeech object , such as its language ,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given below −

The method setLanguage takes an Locale object as parameter. The list of some of the locales available are given below −

Sr.No Locale
1 US
2 CANADA_FRENCH
3 GERMANY
4 ITALY
5 JAPAN
6 CHINA

Once you have set the language, you can call speak method of the class to speak the text. Its syntax is given below −

Apart from the speak method, there are some other methods available in the TextToSpeech class. They are listed below −

addSpeech(String text, String filename)

This method adds a mapping between a string of text and a sound file.

This method returns a Locale instance describing the language.

This method checks whether the TextToSpeech engine is busy speaking.

This method sets the speech pitch for the TextToSpeech engine.

This method sets the speech rate.

This method releases the resources used by the TextToSpeech engine.

This method stop the speak.

Example

The below example demonstrates the use of TextToSpeech class. It crates a basic application that allows you to set write text and speak it.

To experiment with this example , you need to run this on an actual device.

Sr.No Method & description
1
Steps Description
1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add TextToSpeech code.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4 Run the application and choose a running android device and install the application on it and verify the results.

Here is the content of src/MainActivity.java.

Here is the content of activity_main.xml

In the following code abcindicates the logo of tutorialspoint.com

Here is the content of Strings.xml.

Here is the content of AndroidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, android studio will display following window to select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which will display following screen.

Now just type some text in the field and click on the text to speech button below. A notification would appear and text will be spoken. It is shown in the image below −

Now type something else and repeat the step again with different locale. You will again hear sound. This is shown below −

Источник

Android Text to Speech Tutorial

Android is providing a cool feature (from Android 1.6) called Text to Speech (TTS) which speaks the text in different languages. This tutorial explains how to work with android text to speech or android speech synthesis. In this tutorial i also explained changing the language type, pitch level and speed level.

Below i provided video of the ouput.

I developed a simple interface with one input field and a button to trigger a event that will take text from input field and speaks out.

1. Create a new project by going to File ⇒ New Android Project. and fill required details.
2. Implement your main Activity class from TextToSpeech.OnInitListener

3. Now add following code your class.

4. Now run your project and test your app by entering some text in input filed.

You can change language to speak by using setLanguage() function. Lot of languages are supported like Canada, French, Chinese, Germany etc.,

Changing Pitch Rate

You can set speed pitch level by using setPitch() function. By default the value is 1.0 You can set lower values than 1.0 to decrease pitch level or greater values for increase pitch level.

Changing Speed Rate

The speed rate can be set using setSpeechRate(). This also will take default of 1.0 value. You can double the speed rate by setting 2.0 or make half the speed level by setting 0.5

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.

Источник

Android TextToSpeech Example

Android operating system provides developers some of the cool API’s such as Text to speech API. converting Text-To-Speech (TTS) or also known as “speech synthesis”. Text-To-Speech enables your Android device to speak text of different languages.

  1. It is introduced from android 1.6, API Level 4. All of the TTS API’s are available in android.speech.tts.TextToSpeech class.
  2. TTS supports various languages like English, French, German, Italian and Spanish, etc. and some additional languages depending on the region.
  3. You have to pre-configure the Text-To-Speech engine with which language to speak. The initial language configuration is important to initialize the specific voice dictionary.

Following section of this tutorial will teach you the steps required to implement TTS in your Android application.

TextToSpeech Example

Before you go ahead implementing the Text to Speech, you must note the following points

  1. A TextToSpeech instance can only be used to synthesize text once it has completed its initialization.
  2. The constructor of TextToSpeech class takes TextToSpeech.OnInitListener parameter. You must implement the TextToSpeech.OnInitListener to be notified, when the TTS is initialized.
  3. Call speak() method on TextToSpeech instance for making Text to Speech to work.
  4. The speak() method accepts three parameter, a String that accepts text, an integer queue mode and Bundle. The queue mode can be either QUEUE_FLUSH or QUEUE_ADD .

In this example, we have an simple activity with an EditText and button, that allows user to enter text for converting into Speech. A screenshot of output is shown below

Define Activity Layout

As described above, for the sake of simplicity we will be creating the simple layout with an EditText and a Button.

TextToSpeech Manager

In this example, we will be crating a generic class named TTSManager , which will encapsulate all of the logic to implement TextToSpeech in Android. You can reuse the class and use it anywhere you like.

How it works

  1. To make the TTS engine to work, the basic configuration is the language that TTS will initialize. You can set the language just by calling setLanguage(locale) method.
  2. Before we call setLanguage() , you need to check if the specified locale is supported. To query whether a specific Locale is supported, you can use isLanguageAvailable() , which returns the level of support for the given Locale.
  3. The TTS engine manages a global queue of all the entries to synthesize, which are also known as “utterances”.
  4. Each TextToSpeech instance can manage its own queue in order to control which utterance will interrupt the current one and which one is simply queued.

Making your app to speak

Queue multiple texts

If you have multiple text to be queued for TTS engine, you may do it by calling speak() method with TextToSpeech.QUEUE_ADD flag.

How it works

  1. Here in this example, the call to the first speak() method would interrupt whatever was currently being synthesized and the queue is flushed and the new utterance is queued, which places it at the head of the queue.
  2. On the second call to speak() method, the utterance is queued and will be played after myText1 has completed.

Источник

Speech-to-text and Text-to-speech with Android

May 30, 2020 · 3 min read

Have you ever wondered how does Google’s speech search work, or ever thought of building an ebook narration app? At the first glance it might seem some complex piece of technology. While it is complicated to implement it on your own, thankfully Android (via Google Services) has built in speech-to-text and text-to-speech APIs which make it extremely easy to setup these features.

See it in action

How does this work?

For Speech-to-text, Android provides a n Intent based API which launches Google’s Speech Recognition service and returns back the text result to you. There is a catch though — the device will require Google Search app for the service to work.

The Text-to-speech API, unlike Speech Recognition, is available without Google Services, and can be found in android.speech.tts package.

Source code

You can find the source of this tutorial on GitHub.

Let’s develop!

Fire up Android Studio and create a project with a Blank Activity.

User interface

The user interface is going to be simple — a LinearLayout as the root view group, inside wich there will be a Button which launches the Speech Recognition API, an EditText that shows the Speech Recognition output as well as serves as input to Text-to-speech functionality, and another Button to trigger Text-to-speech output.

The resultant XML file is as follows:

Setting up speech recognition

Unlike Speech Recognition API, Text-to-speech has it own class and doesn’t run on Intents. We’ll start off by creating a TextToSpeech object. The TextToSpeech class constructor expects a Context and an OnInitListener .

Then, we’ll set an OnClickListener to our TTS button and call the text-to-speech API on our input text.

As a safety measure and to prevent memory leaks, we must override onPause and onDestroy methods and appropriately stop or shutdown the TextToSpeech object.

And that’s it. Give it a try!

Closing Thoughts

With the standard APIs, Speech Recognition (or Speech-to-text) and Text-to-speech in Android is extremely easy to implement. While this might suffice most use cases, some advanced use cases would require more sophisticated third-party APIs or a custom implementation in your backend. We’ll probably cover that sometime later.

Until then, keep coding, and as always do let me know if you have any questions in the comments section!

Источник

Android SDK: Using the Text to Speech Engine

This tutorial will teach you to give your applications a voice with the Android SDK text to speech engine!

The Android text to speech engine still seems to be a pretty underused resource in Android apps. However, implementing it in your own applications is straightforward. There are a few potential issues and choices you need to consider, but for most purposes, the process is not a complex one. In this tutorial we jump around a bit within one Android Activity, but don’t worry, the complete code is listed at the end. The aim is to give you a clear idea of the what’s going on at each processing stage so that you can successfully use the function in any app.

Step 1: Start or Open an Android Project

If you already have an application you want to implement Text To Speech with, open it in your IDE. Otherwise, create a new Android project. You can use the code in this tutorial with any Activity class. For demonstration, we will first create some user interface elements. Again, if you already have your own UI, you can use it instead.

Step 2: Create User Interface Elements

Add some user interface elements to your application, allowing the user to enter text and initiate speech playback using a button. In the XML layout file for your Activity, which will be «main.xml» if you created a new project, add the following markup:

Your XML layout files should be in the «res/layout» directory within your application package. This code adds three user interface elements: a label with some instructional text in it, an editable text-field, and a button. The user will be able to enter text into the field, then press the button to hear it spoken. If you are using an existing project, you can of course use the interface elements you already have. If you are using these new elements, you can alter them to suit the design of your own app.

Step 3: Listen For User Events

Open the Java file for the Activity you want to implement TTS in. If you created a new app, open the main class file. In Eclipse, your Activity should automatically have the «onCreate» method within it and should extend «Activity» as part of its declaration. At the top of the class file, add the following import statements so that your app can listen for button clicks:

Alter the class declaration to implement the «OnClickListener» interface, as in the following sample line of code:

Alter the class name to suit your own application details. Your IDE may display warnings because your class has not yet implemented «OnClickListener» correctly — just ignore these for now. In the «onCreate» method, add the following code:

If you did not add the button using «speak» as its ID in your XML layout file, alter this code to reflect the correct ID value. This sets your Activity class up to handle user button clicks. Add the following method outline to your class:

Inside this method you will begin the Text To Speech functionality.

Step 4: Get the Entered Text

When the user clicks the button, your app needs to get any text entered so that you can pass it to the TTS method. Add the following import statement at the top of your class declaration so that your code can refer to the editable text-field:

Inside your «onClick» method, add the following code:

This code first acquires a reference to the text-field using its ID value, so alter this if you used a different value in your layout XML. Next, the code gets the text from the field and stores it as a string variable. If the user has not entered any text this will be empty. Depending on the logic within your application you may wish to add a conditional test, checking that the string is not null or zero in length, but this is not generally necessary.

Step 5: Create a Speech Method

To keep your Android classes well-organized, it’s advisable to create dedicated methods for processes you may want to use more than once. Add the following method outline to your Activity:

This is where your TTS processing will go. Back in the «onClick» listener method, call this new method, passing it the string variable your code copied from the text-field:

Using a method for the TTS process means that your code can call on it elsewhere if necessary.

Step 6: Implement TTS Within the Class

To utilize the TTS facility, you need to make a few more changes to your class declaration. Add the following import statements for the TTS classes at the top of your file:

You also need to implement one more interface, so alter your class declaration outline to add «OnInitListener» as in the following example:

Remember to use your own class name. Again, your IDE will alert you to the fact that you haven’t yet implemented this interface but don’t worry, you will soon.

Step 7: Check for TTS Data

Your app needs to check that the user has the data necessary for the TTS function before you call its methods. Declare and instantiate the following instance variable at the top of your Activity class declaration, before the «onCreate» method:

Add the following import statement at the top of the class:

In the «onCreate» method, add the following:

This code creates a new Intent purely for the purposes of checking the user data. When the checking process is complete, the code will call the «onActivityResult» method.

Step 8: Create a TTS Instance

Declare an instance variable for your TTS object at the top of the class declaration, also before the «onCreate» method:

Add the «onActivityResult» to your class as follows:

When the data checking Intent completes, the app calls this method, passing it the «MY_DATA_CHECK_CODE» variable indicating whether or not the user has the TTS data installed. If the data is present, the code goes ahead and creates an instance of the TTS class. If the data is not present, the app will prompt the user to install it.

Step 9: Provide the onInit Method

Your class declaration is implementing «OnInitListener» so you must provide an «onInit» method. In this method, you can carry out any final set-up checks you need, as well as choosing settings for your TTS instance, such as language and locale options. Add the following import statement at the top of your class:

Add the «onInit» method to the class as follows:

This code checks that the TTS resource is successfully instantiated, then sets a US English Locale for the speech operations. You can optionally output an error message for users if the TTS does not successfully instantiate by adding the following after the «if» block:

If you use this code you will also need to import the Toast class by adding the following statement at the top of your file:

Your app can carry out checks on the user device, such as available languages, as in the following extended version of the statement creating the TTS object inside the first conditional statement:

Step 10: Speak!

Finally, your app is ready to speak. Inside the «speakWords» method, add the following code:

There are lots of options here in terms of how your app handles speech. This code instructs the app to speak the text string immediately. If you want to add consecutive speech operations, you can instruct the app to wait until any current speech operations finish by adding your new speech item to a queue, as follows:

Once your class is finished with the TTS, you can optionally shut it down as follows:

Don’t include this line if you want your users to be able to make the app speak more than once.

Conclusion

To see how all of these elements fit together, here is the complete class declaration:

Remember to use your own class name and to indicate your application package at the top of the file. If you are using Eclipse, you should not need to add all of the import statements manually, as the IDE will insert some of them automatically. Run your app in the Android emulator and hear it in action.

This is a basic overview of implementing Text To Speech in your Android apps. The TTS resource provides a wide range of additional options you may want to explore depending on the nature of your apps. When calling the TextToSpeech object «speak» method for example, you can pass a HashMap object indicating the details of more complex playback options.

Источник

Читайте также:  Простейший компас для андроида
Оцените статью