A brief introduction to Android voice broadcast TTS

About the author: Xiaobei Programming (focusing on HarmonyOS, Android, Java, Web, TCP/IP and other technical directions)
Blog homepage: Open Source China, Rare Earth Nuggets, 51cto Blog, Blog Park, Zhihu, Jianshu, MOOC, CSDN
If the article is helpful to you, please follow, like, collect, and comment.
If you need to reprint, please refer to [Reprint Instructions]

In modern mobile application development, speech synthesis technology (TTS) plays an increasingly important role. The Android platform provides a rich TTS API that allows developers to easily convert text into natural and smooth speech. This article will introduce the basic concepts, usage and some best practices of Android TTS technology.

What is Android TTS?

Android TTS refers to Android Text-to-Speech technology, which allows developers to programmatically convert text to speech. This technology is critical for building accessible apps, voice assistants, voice navigation, and other voice-interactive applications.

Using Android TTS API

The Android TTS API provides a rich set of methods and callbacks for controlling various aspects of speech synthesis. Here’s a simple example of how to use the TTS API in an Android app:

Android TTS (Text-to-Speech) provides a series of methods for controlling the text-to-speech conversion process. The following are commonly used methods in Android TTS:

TextToSpeech(Context context, TextToSpeech.OnInitListener listener): Constructor, used to initialize the TTS engine.

setLanguage(Locale loc): Set the language of the TTS engine.

speak(String text, int queueMode, HashMap<String, String> params): Convert the specified text into speech and play it.

stop(): Stop the current speech synthesis.

shutdown(): Release the resources of the TTS engine.

setPitch(float pitch): Set the pitch of the voice.

setSpeechRate(float speechRate): Set the speech rate of the voice.

isSpeaking(): Checks whether speech synthesis is currently in progress.

These methods allow developers to control various aspects of the TTS engine, including language settings, text synthesis, speech parameter adjustment, etc. By using these methods appropriately, developers can implement customized speech synthesis functions to meet the needs of different application scenarios.

If we are going to use it first, make sure your application has the appropriate permissions. Add the following permissions in the AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

The simplest example:

TextToSpeech tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            tts.setLanguage(Locale.US);
            tts.speak("Hello, welcome to the TTS demo.", TextToSpeech.QUEUE_FLUSH, null, null);
        } else {
            Log.e("TTS", "Initialization failed");
        }
    }
});

// Release TTS resources when Activity is destroyed
@Override
protected void onDestroy() {
    if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

The following are self-encapsulated tool classes that you can use directly if you want to use them

/**
 * Copyright (C) 2023-2024 Author
 *
 * TTS voice broadcast tool class
 *
 * @author xiaolu
 * @date 2023/11/10
 * @version 1.0.0
 */
public class TTSUtil {
    private TextToSpeech textToSpeech;
    private Context context;
    private boolean initialized = false;
    private float defaultSpeechRate = 1.0f; //Default speech rate
    private float defaultPitch = 1.0f; //Default pitch
    private Locale defaultLocale = Locale.CHINESE; //Default language
    private String utteranceId = "utteranceId"; // unique identifier

    public interface TTSListener {
        void onInitSuccess();
        void onInitFailure();
        void onSpeechStart();
        void onSpeechDone();
        void onSpeechError(String errorMessage);
    }

    public TTSUtil(Context context, final TTSListener listener) {
        this.context = context;
        textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    initialized = true;
                    if (listener != null) {
                        listener.onInitSuccess();
                    }
                } else {
                    if (listener != null) {
                        listener.onInitFailure();
                    }
                }
            }
        });
    }

    //Set the default speaking speed
    public void setDefaultSpeechRate(float speechRate) {
        defaultSpeechRate = speechRate;
    }

    //Set the default tone
    public void setDefaultPitch(float pitch) {
        defaultPitch = pitch;
    }

    //Set default language
    public void setDefaultLocale(Locale locale) {
        defaultLocale = locale;
    }

    // text to speech
    public void speak(String text) {
        speak(text, utteranceId);
    }

    public void speak(String text, String utteranceId) {
        speak(text, utteranceId, defaultLocale, defaultSpeechRate, defaultPitch);
    }

    public void speak(String text, String utteranceId, Locale locale, float speechRate, float pitch) {
        if (initialized) {
            textToSpeech.setLanguage(locale);
            textToSpeech.setSpeechRate(speechRate);
            textToSpeech.setPitch(pitch);

            HashMap<String, String> params = new HashMap<>();
            params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);

            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, params);
            textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                @Override
                public void onStart(String utteranceId) {
                    Logger.d("TTS TTSUtil onStart: " + utteranceId);
                }

                @Override
                public void onDone(String utteranceId) {
                    Logger.d("TTS TTSUtil onDone: " + utteranceId);
                }

                @Override
                public void onError(String utteranceId) {
                     Logger.d("TTS TTSUtil onError: " + utteranceId);
                }
            });
        }
    }

    // Release resources
    public void release() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
    }
}

layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:ignore="MissingDefaultResource,Orientation">

    <TextView
        android:id="@ + id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textSize="20dp"
        android:text="No matter how big the challenge is, you have enough strength to overcome it. Every step of effort is part of the road to success. Don't forget that your dreams and goals are worth pursuing, and you Every effort you make is a key step towards success. Persevere, work hard, and believe in yourself, and you will be able to create a better tomorrow. You are unique and your abilities are unlimited. Believe in yourself and you can surpass yourself. expectations and create amazing achievements. In the face of every difficulty, there are opportunities and growth. Maintain a positive attitude and move forward courageously, and you will find that you can reach unexpected heights. I wish you, in your journey of life, Move forward bravely, dare to dream, and pursue bravely, and your future will become more brilliant."/>

    <Button
        android:id="@ + id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:text="Click to test TTS voice"/>
</LinearLayout>

Example:

 private TTSUtil ttsUtil;
 //Create a TTSUtil instance and pass in Context and TTSListener
        ttsUtil = new TTSUtil(this, new TTSUtil.TTSListener() {
            @Override
            public void onInitSuccess() {
                // TTS engine initialization successful
                // Here you can perform speech synthesis operations
                String text = "Voice initialization successful";
                ttsUtil.speak(text);
                Logger.e("TTS TTSUtil onInitSuccess voice initialization successful");
            }

            @Override
            public void onInitFailure() {
                Logger.e("TTS TTSUtil onInitFailure TTS engine initialization failed");
            }

            @Override
            public void onSpeechStart() {
                Logger.e("TTS TTSUtil onSpeechStart speech synthesis starts");
            }

            @Override
            public void onSpeechDone() {
                Logger.e("TTS TTSUtil onSpeechDone speech synthesis completed");
            }

            @Override
            public void onSpeechError(String errorMessage) {
                Logger.e("TTS TTSUtil onSpeechError speech synthesis error " + errorMessage);
            }
        });

        binding.button.setOnClickListener(v -> {
            ttsUtil.speak(binding.textView.getText().toString().trim());
        });

Android TTS technology provides developers with powerful tools for building various voice interaction applications. By using the TTS API appropriately and following best practices, developers can provide users with a smarter and more convenient application experience. With the continuous development of TTS technology, I believe that it will show its strong potential in more fields in the future.

No matter what stage you are at, persistence is the key to success. Don’t stop and keep moving forward. Even if the road ahead is rough, stay optimistic and courageous. Believe in your abilities and the goals you pursue will be achieved in the near future. come on!