使用TextToSpeech實現文字轉音訊(自動朗讀)
阿新 • • 發佈:2019-01-30
主要方法
setLanguage:設定語言的型別
speak:傳入文字播放聲音
synthesizeToFile:傳入文字儲存為音訊
shutdown:釋放TextToSpeech資源
package prictise.lxm.prictise; 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 android.widget.Toast; import java.util.Locale; /** * 使用TextToSpeech實現自動朗讀 */ public class MainActivity extends Activity{ TextToSpeech textToSpeech; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取介面檢視 final EditText edTxtSpeak = (EditText)findViewById(R.id.edTxt_speak); final Button btnSpeak = (Button)findViewById(R.id.btn_speak); final Button btnSave = (Button)findViewById(R.id.btn_save); textToSpeech = new TextToSpeech(this,new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { //初始化成功,設定語言 if(status == TextToSpeech.SUCCESS){ //設定語言為美式英語 int result = textToSpeech.setLanguage(Locale.US); //設定語言為中文 // int result = textToSpeech.setLanguage(Locale.CHINA); if(result != TextToSpeech.LANG_AVAILABLE && result != TextToSpeech.LANG_COUNTRY_AVAILABLE){ //不支援當前語言 Toast.makeText(MainActivity.this,"不支援" + textToSpeech.getLanguage(). getDisplayName(),Toast.LENGTH_SHORT).show(); //設定發音按鈕不可用 btnSave.setEnabled(false); btnSpeak.setEnabled(false); } } } }); //播放按鈕 btnSpeak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textToSpeech.speak(edTxtSpeak.getText().toString(),TextToSpeech.QUEUE_ADD,null); } }); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textToSpeech.synthesizeToFile(edTxtSpeak.getText().toString(),null,"speakUs"); } }); } protected void onDestroy() { //釋放tts if(textToSpeech != null) { textToSpeech.shutdown(); } super.onDestroy(); } }