1.介绍
2.xml文件布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" android:gravity="center_horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="请输入需要朗读的文字:" /> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" android:text="" /> </LinearLayout> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="朗读" /> </LinearLayout>
3.java后台代码
package com.lucky.test43tts; import android.speech.tts.TextToSpeech; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.Locale; public class MainActivity extends AppCompatActivity { Button button1; EditText editText; TextToSpeech textToSpeech;//定义一个TTS @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1=findViewById(R.id.button2); editText=findViewById(R.id.editText); //实例化TTS textToSpeech=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { textToSpeech.setLanguage(Locale.CHINESE); //设置朗读的语言类型 } }); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //朗读内容 textToSpeech.speak(editText.getText().toString(),TextToSpeech.QUEUE_ADD,null); } }); } }