歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android的數據存儲和IO - 自動朗讀(TTS)

Android的數據存儲和IO - 自動朗讀(TTS)

日期:2017/3/1 10:14:59   编辑:Linux編程

Android的數據存儲和IO - 自動朗讀(TTS)

自動朗讀又是Android提供的另一種另類的IO,蠻不錯的哦,支持對指定文本內容進朗讀,學習完這個內容我立馬就讓它朗讀:wwj is a good man.作為一個自我滿足。

創建項目:Speech

運行效果:

Activity文件:Speech.java

  1. package wwj.speech;
  2. import java.util.Locale;
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.speech.tts.TextToSpeech;
  6. import android.speech.tts.TextToSpeech.OnInitListener;
  7. import android.view.View;
  8. import android.view.View.OnClickListener;
  9. import android.widget.Button;
  10. import android.widget.EditText;
  11. import android.widget.Toast;
  12. public class Speech extends Activity {
  13. TextToSpeech tts;
  14. EditText editText;
  15. Button speech;
  16. Button record;
  17. @Override
  18. public void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.main);
  21. //初始化TextToSpeech對象
  22. tts = new TextToSpeech(this, new OnInitListener() {
  23. public void onInit(int status) {
  24. // TODO Auto-generated method stub
  25. //如果裝載TTS引擎成功
  26. if(status == TextToSpeech.SUCCESS){
  27. //設置使用美式英語朗讀
  28. int result = tts.setLanguage(Locale.US);
  29. //如果不支持所設置的語言
  30. if(result != TextToSpeech.LANG_COUNTRY_AVAILABLE
  31. && result != TextToSpeech.LANG_AVAILABLE){
  32. Toast.makeText(Speech.this, "TTS暫時不支持這種語言的朗讀。", 50000).show();
  33. }
  34. }
  35. }
  36. });
  37. editText = (EditText)findViewById(R.id.txt);
  38. speech = (Button) findViewById(R.id.speech);
  39. record = (Button) findViewById(R.id.record);
  40. speech.setOnClickListener(new OnClickListener() {
  41. public void onClick(View v) {
  42. // TODO Auto-generated method stub
  43. //執行朗讀
  44. tts.speak(editText.getText().toString(), TextToSpeech.QUEUE_ADD, null);
  45. }
  46. });
  47. record.setOnClickListener(new OnClickListener() {
  48. public void onClick(View v) {
  49. // TODO Auto-generated method stub
  50. //將朗讀文本的音頻記錄到指定文件
  51. tts.synthesizeToFile(editText.getText().toString(), null, "/mnt/sdcard/sound.wav");
  52. Toast.makeText(Speech.this, "聲音記錄成功! ", 50000).show();
  53. }
  54. });
  55. }
  56. @Override
  57. protected void onDestroy() {
  58. // TODO Auto-generated method stub
  59. //關閉TextToSpeech對象
  60. if(tts != null){
  61. tts.shutdown();
  62. }
  63. super.onDestroy();
  64. }
  65. }

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved