Android 1.6開始支持TTS(Text To Speech)技術,經過該技術能夠將文本轉換成語音。java
TTS技術的核心是android.speech.tts.TextToSpeech類。要想使用TTS技術朗讀文本,須要作兩個工做:初始化TTS和指定要朗讀的文本。在第1項工做中主要指定TTS朗讀的文本的語言,第2項工做主要使用speak方法指定要朗讀的文本。android
TextToSpeech.OnInitListener.onInit用於初始化TTSapp
TextToSpeech.speak用於將文本轉換爲聲音ide
1 import java.util.Locale; 2 3 import android.annotation.SuppressLint; 4 import android.app.Activity; 5 import android.os.Bundle; 6 import android.speech.tts.TextToSpeech; 7 import android.view.View; 8 import android.view.View.OnClickListener; 9 import android.widget.Button; 10 import android.widget.TextView; 11 import android.widget.Toast; 12 13 @SuppressLint("NewApi") 14 15 /** 16 * 朗讀文本 17 * 18 * 安卓自己的庫,只支持英文。除非從網上更新下載其餘語言包。 19 * @author dr 20 */ 21 public class Main extends Activity implements TextToSpeech.OnInitListener, 22 OnClickListener { 23 private TextToSpeech tts; 24 private TextView textView; 25 26 @SuppressLint("NewApi") 27 @Override 28 public void onCreate(Bundle savedInstanceState) { 29 super.onCreate(savedInstanceState); 30 setContentView(R.layout.main); 31 32 tts = new TextToSpeech(this, this); 33 34 Button button = (Button) findViewById(R.id.button); 35 textView = (TextView) findViewById(R.id.textview); 36 button.setOnClickListener(this); 37 } 38 39 public void onClick(View view) { 40 tts.speak(textView.getText().toString(), TextToSpeech.QUEUE_FLUSH, null); 41 } 42 43 @Override 44 public void onInit(int status) { 45 if (status == TextToSpeech.SUCCESS) { 46 int result = tts.setLanguage(Locale.US); 47 if (result == TextToSpeech.LANG_MISSING_DATA 48 || result == TextToSpeech.LANG_NOT_SUPPORTED) { 49 Toast.makeText(this, "Language is not available.", 50 Toast.LENGTH_LONG).show(); 51 } 52 } 53 54 } 55 56 }