Android的數據存儲和IO - 自動朗讀(TTS)
自動朗讀又是Android提供的另一種另類的IO,蠻不錯的哦,支持對指定文本內容進朗讀,學習完這個內容我立馬就讓它朗讀:wwj is a good man.作為一個自我滿足。
創建項目:Speech
運行效果:
Activity文件:Speech.java
- package wwj.speech;
-
- import java.util.Locale;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.speech.tts.TextToSpeech;
- import android.speech.tts.TextToSpeech.OnInitListener;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
-
- public class Speech extends Activity {
-
- TextToSpeech tts;
- EditText editText;
- Button speech;
- Button record;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //初始化TextToSpeech對象
- tts = new TextToSpeech(this, new OnInitListener() {
-
- public void onInit(int status) {
- // TODO Auto-generated method stub
- //如果裝載TTS引擎成功
- if(status == TextToSpeech.SUCCESS){
- //設置使用美式英語朗讀
- int result = tts.setLanguage(Locale.US);
- //如果不支持所設置的語言
- if(result != TextToSpeech.LANG_COUNTRY_AVAILABLE
- && result != TextToSpeech.LANG_AVAILABLE){
- Toast.makeText(Speech.this, "TTS暫時不支持這種語言的朗讀。", 50000).show();
- }
- }
- }
- });
- editText = (EditText)findViewById(R.id.txt);
- speech = (Button) findViewById(R.id.speech);
- record = (Button) findViewById(R.id.record);
- speech.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- // TODO Auto-generated method stub
- //執行朗讀
- tts.speak(editText.getText().toString(), TextToSpeech.QUEUE_ADD, null);
- }
- });
- record.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- // TODO Auto-generated method stub
- //將朗讀文本的音頻記錄到指定文件
- tts.synthesizeToFile(editText.getText().toString(), null, "/mnt/sdcard/sound.wav");
- Toast.makeText(Speech.this, "聲音記錄成功! ", 50000).show();
- }
- });
- }
- @Override
- protected void onDestroy() {
- // TODO Auto-generated method stub
- //關閉TextToSpeech對象
- if(tts != null){
- tts.shutdown();
- }
- super.onDestroy();
- }
- }
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11