如何让Android手机读取文本呢?Android SDK为开发者提供了TTS技术,开发者只需要做简单的调用就可以完成让Android读取文本的功能。
示例的功能是点击按钮后,朗读TextVeiw中的文本,UI如下:
对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);
}
@Override
public void onClick(View v) {
if (textToSpeech != null && !textToSpeech.isSpeaking()) {
textToSpeech.speak(speechText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
}
@Override
public 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();
}
}
}
@Override
protected void onStop() {
super.onStop();
textToSpeech.stop();
textToSpeech.shutdown();
}
}
希望对你有所帮助,如需代码,请点击此处!=^_^=
参考:http://developer.android.com/reference/android/speech/tts/TextToSpeech.html