22、TTS技术

Android对TTS技术的支持

      Android 1.6开始支持TTS(Text To Speech)技术,通过该技术可以将文本转换成语音。

     TTS技术的核心是android.speech.tts.TextToSpeech类。要想使用TTS技术朗读文本,需要做两个工作:初始化TTS和指定要朗读的文本。在第1项工作中主要指定TTS朗读的文本的语言,第2项工作主要使用speak方法指定要朗读的文本。

在Android中使用TTS技术

TextToSpeech.OnInitListener.onInit用于初始化TTS

TextToSpeech.speak用于将文本转换为声音

Demo
 
 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 }

 

你可能感兴趣的:(tts)