首先感謝原文的博主,本文中的代碼均來自該博主:(原文地址)http://flycatdeng.iteye.com/blog/1827245
朗讀文字不需要任何的權限,這個控件的好處是首先不要權限,其次不用聯網避免了如訊飛的聯網登權限(訊飛其實也不錯,比較智能,該控件只能讀取簡單的文字)
布局文件
<?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:context="com.lizhanqi.www.androidtexttospeech.MainActivity"> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="請輸入要朗誦的字" /> <Button android:id="@+id/btn_read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="讀" /> </LinearLayout>
//代碼
package com.lizhanqi.www.androidtexttospeech; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.Locale; public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextToSpeech.OnInitListener { private Button speechBtn; // 按鈕控制開始朗讀 private EditText speechTxt; // 需要朗讀的內容 private TextToSpeech textToSpeech; // TTS對象 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); speechBtn = (Button) findViewById(R.id.btn_read); speechBtn.setOnClickListener(this); speechTxt = (EditText) findViewById(R.id.editText); textToSpeech = new TextToSpeech(this, this); // 參數Context,TextToSpeech.OnInitListener } /** * 用來初始化TextToSpeech引擎 * status:SUCCESS或ERROR這2個值 * setLanguage設置語言,幫助文檔里面寫了有22種 * TextToSpeech.LANG_MISSING_DATA:表示語言的數據丟失。 * TextToSpeech.LANG_NOT_SUPPORTED:不支持 */ @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = textToSpeech.setLanguage(Locale.CHINA); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Toast.makeText(this, "數據丟失或不支持", Toast.LENGTH_SHORT).show(); } } } @Override public void onClick(View v) { if (textToSpeech != null && !textToSpeech.isSpeaking()) { textToSpeech.setPitch(0.0f);// 設置音調,值越大聲音越尖(女生),值越小則變成男聲,1.0是常規 textToSpeech.speak(speechTxt.getText().toString(), TextToSpeech.QUEUE_FLUSH, null); } } @Override protected void onStop() { super.onStop(); textToSpeech.stop(); // 不管是否正在朗讀TTS都被打斷 textToSpeech.shutdown(); // 關閉,釋放資源 } }