最近在作一個項目,其中有一個功能是須要將文本轉換成語音並播放出來。下面我將個人作法分享一下。java
很是使人開心的是,Android
系統目前已經集成了TTS
,提供了相關的庫供咱們進行調用,沒必要處處去搜尋第三方庫,直接導入android.speech.tts.TextToSpeech
便可。android
//導入TTS的包 import android.speech.tts.TextToSpeech; //定義一個tts對象 private TextToSpeech tts;
其次,要想實例化這個對象須要兩個參數,一個是Context
對象,另外一個是TextToSpeech
類對應的監聽器對象:OnLnitListener
對象。通常Context
對象傳入當前的Activity
,OnLnitListener
能夠本身寫類繼承,並實現其方法。git
//導入監聽包 import android.speech.tts.TextToSpeech.OnInitListener; //初始化tts監聽對象 tts = new TextToSpeech(this, OnInitListener);
OnLnitListener
接口中只要是onInit
方法,其功能是對tts
對象進行初始化,設置一下語言,判斷文字是否轉換成功以及當前系統是否支持該語言。github
@Override public void onInit(int status){ // 判斷是否轉化成功 if (status == TextToSpeech.SUCCESS){ //默認設定語言爲中文,原生的android貌似不支持中文。 int result = tts.setLanguage(Locale.CHINESE); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){ Toast.makeText(MainActivity.this, R.string.notAvailable, Toast.LENGTH_SHORT).show(); }else{ //不支持中文就將語言設置爲英文 tts.setLanguage(Locale.US); } } }
最後,只要在合適的時候調用tts轉文字到語音的方法便可.微信
tts.speak("須要轉化的文字", TextToSpeech.QUEUE_FLUSH, null);
下面是寫的一個demo:app
MainActivity.java:ide
/** * Author: sandy * QQ技術交流羣:439261058 * 微信公衆號:代碼之間(codestravel) **/ package com.example.ct_text2speechdemo; import java.util.Locale; import android.os.Bundle; import android.app.Activity; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnInitListener{ //定義控件 private Button speechButton; private TextView speechText; private TextToSpeech tts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化TTS tts = new TextToSpeech(this, this); //獲取控件 speechText = (TextView)findViewById(R.id.speechTextView); speechButton = (Button)findViewById(R.id.speechButton); //爲button添加監聽 speechButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v){ // TODO Auto-generated method stub tts.speak(speechText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null); } }); } @Override public void onInit(int status){ // 判斷是否轉化成功 if (status == TextToSpeech.SUCCESS){ //默認設定語言爲中文,原生的android貌似不支持中文。 int result = tts.setLanguage(Locale.CHINESE); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){ Toast.makeText(MainActivity.this, R.string.notAvailable, Toast.LENGTH_SHORT).show(); }else{ //不支持中文就將語言設置爲英文 tts.setLanguage(Locale.US); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
完整代碼參見 https://github.com/codestravel/CT_Android_demos/tree/master/CT_Text2SpeechDemo
this
歡迎加入qq技術交流羣:439261058code
微信公衆號:代碼之間(codestravel)對象