wangleyiang 发表于 2013-1-30 04:04:11

Android TextToSpeech简单使用

    如何让Android手机读取文本呢?Android SDK为开发者提供了TTS技术,开发者只需要做简单的调用就可以完成让Android读取文本的功能。
    示例的功能是点击按钮后,朗读TextVeiw中的文本,UI如下:

http://dl.iteye.com/upload/attachment/0075/9532/e94ebee4-74b9-37e3-9d6d-09c7285455d0.png
     对TextToSpeech的实例添加OnInitListener()和OnUtteranceCompletedListener()来实现对TTS状态的监听,并在需要时,添加自己的逻辑代码。这个功能的核心代码如下:
package com.anhuioss.tts;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.TextView;import android.widget.Toast;public class TTSActivity extends Activity implements OnClickListener, OnInitListener {Button speechButton;TextView speechText;TextToSpeech textToSpeech;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.main);                speechButton = (Button) findViewById(R.id.button1);      speechText = (TextView) findViewById(R.id.textView1);                speechButton.setOnClickListener(this);                textToSpeech = new TextToSpeech(this, this);            }@Overridepublic void onClick(View v) {if (textToSpeech != null && !textToSpeech.isSpeaking()) {textToSpeech.speak(speechText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);}}@Overridepublic void onInit(int status) {if (status == TextToSpeech.SUCCESS) {int result = textToSpeech.setLanguage(Locale.US);if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {Toast.makeText(this, "Denotes the language data is missing or the language is not supported.", Toast.LENGTH_SHORT).show();}}}@Overrideprotected void onStop() {super.onStop();textToSpeech.stop();textToSpeech.shutdown();}}     希望对你有所帮助,如需代码,请点击此处!=^_^=
    参考:http://developer.android.com/reference/android/speech/tts/TextToSpeech.html
页: [1]
查看完整版本: Android TextToSpeech简单使用