简单的文本语音朗读功能实现
实现这个功能主要用一个类,是TextToSpeech,废话不都少,直接上代码。总的来说效果一般,短语的停顿节奏不是很好。
界面很简单,一个Button ,一个EditView,就不贴代码了
public class ActivityResumptionArticle extends BaseActivity{
private TextToSpeech mSpeech = null;
private Button btn = null;
private EditTextView ev = null;
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_resumption_article);
//测试朗读功能
btn = (Button) findViewById(R.id.but);
ev = (EditView)findViewById(R.id.ev);
mSpeech = new TextToSpeech(this, new OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
//下面这句代码是主要的,设置语言,如果是英文的话,就用Locale.ENGLISH
int result = mSpeech.setLanguage(Locale.CHINA);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("lanageTag", "not use");
} else {
btn.setEnabled(true);
mSpeech.speak("i love you", TextToSpeech.QUEUE_FLUSH,
null);
}
}
}
});
//进度监听器,有点粗糙,但够用了,记得在done后将mpeech shutdown
mSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
}
@Override
public void onError(String utteranceId) {
}
@Override
public void onDone(String utteranceId) {
mSpeech.shutdown();
}
});
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 开始朗读
mSpeech.speak(ev.getText().toString(),
TextToSpeech.QUEUE_FLUSH, null);
}
});
}
}
android语音朗读功能demo实现