Android 简明教程

Android - Text To Speech

Android 允许您将文本转换为语音。它不仅允许您这么做,还允许您用多种不同的语言朗读文本。

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 提供 TextToSpeech 类用于此目的。为了使用这个类,您需要实例化这个类的对象,并指定 initListener 。其语法如下:

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 −

private EditText write;
ttobj=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
   @Override
   public void onInit(int status) {
   }
});

在此监听器中,您必须指定 TextToSpeech 对象的属性,例如其语言、音调等。可以通过调用 setLanguage() 方法来设置语言。其语法如下:

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 −

ttobj.setLanguage(Locale.UK);

setLanguage 方法将 Locale 对象作为参数。以下将列出可用的某些区域设置的列表:

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

一旦设置了语言,您可以调用该类的 speak 方法来朗读文本。其语法如下:

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

ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);

除了 speak 方法之外,TextToSpeech 类还提供一些其他方法。它们列在下面:

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

Sr.No

Method & description

1

addSpeech(String text, String filename) This method adds a mapping between a string of text and a sound file.

2

getLanguage() This method returns a Locale instance describing the language.

3

isSpeaking() This method checks whether the TextToSpeech engine is busy speaking.

4

setPitch(float pitch) This method sets the speech pitch for the TextToSpeech engine.

5

setSpeechRate(float speechRate) This method sets the speech rate.

6

shutdown() This method releases the resources used by the TextToSpeech engine.

7

stop() This method stop the speak.

Example

下面的示例演示了 TextToSpeech 类的使用方法。它创建一个基本的应用程序,允许您设置书写文本并朗读它。

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.

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.

以下为 src/MainActivity.java 的内容。

Here is the content of src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;

public class MainActivity extends Activity {
   TextToSpeech t1;
   EditText ed1;
   Button b1;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      ed1=(EditText)findViewById(R.id.editText);
      b1=(Button)findViewById(R.id.button);

      t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
         @Override
         public void onInit(int status) {
            if(status != TextToSpeech.ERROR) {
               t1.setLanguage(Locale.UK);
            }
         }
      });

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String toSpeak = ed1.getText().toString();
            Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
            t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
         }
      });
   }

   public void onPause(){
      if(t1 !=null){
         t1.stop();
         t1.shutdown();
      }
      super.onPause();
   }
}

以下是 activity_main.xml 的内容。

Here is the content of activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">

   <TextView android:text="Text to Speech" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:layout_below="@+id/imageView"
      android:layout_marginTop="46dp"
      android:hint="Enter Text"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:textColor="#ff7aff10"
      android:textColorHint="#ffff23d1" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Text to Speech"
      android:id="@+id/button"
      android:layout_below="@+id/editText"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="46dp" />

</RelativeLayout>

以下是 Strings.xml 的内容。

Here is the content of Strings.xml.

<resources>
   <string name="app_name">My Application</string>
</resources>

以下是 AndroidManifest.xml 的内容

Here is the content of AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN" >
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>

   </application>
</manifest>

我们尝试运行您的应用程序。我假设您已将实际的安卓移动设备连接到您的电脑。要从 Android Studio 运行应用程序,请打开您项目的某个活动文件,然后从工具栏中点击运行图标。在启动您的应用程序之前,Android Studio 将显示以下窗口,供您选择运行安卓应用程序的位置。

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.

choose device

选择您的移动设备作为选项,然后查看您的移动设备,它将显示以下屏幕。

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

texttospeech

现在,只需在字段输入一些文字,然后单击下面的语音合成按钮。将出现一条通知并且朗读出文字。它显示在下图中 −

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 −

texttospeech1

现在键入其他内容,并以不同的语言环境重复此步骤。您又会听到声音。如下所示 −

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

texttospeech2