您的位置:首页 > 移动开发 > Android开发

Android 轻松实现语音朗读

2010-08-13 20:24 330 查看
语音朗读,这是一个很好的功能,可以实现一些客户的特殊要求。在Android 实现主意功能只需要几段简单的代码即可完成。



在Android 中使用语音朗读功能 只需要使用此类 TextToSpeech ,该类实现了很多关于语音的功能,使用该类必须为其设置语言,支持语言列表位于java.util类里的Local 类,具体如下:



屏幕问题,显示不足,大家可以去SDK查看。虽然支持众多主意列表,可是貌似Android 内置语音朗读的语言种类并不多,是不是以后得在写系统的时候编进去还是怎么样,这个不知所以然,目前我只测试了English 和 Chinese。 English 是可行的,Chinese 失败了。OK ,废话不多说, 上全部实现代码:

package com.terry;

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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class speechActivity extends Activity {
private TextToSpeech mSpeech;
private Button btn;

private EditText mEditText;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btn = (Button) findViewById(R.id.Button01);
mEditText = (EditText) findViewById(R.id.EditText01);
btn.setEnabled(false);
mSpeech = new TextToSpeech(this, new OnInitListener() {

@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = mSpeech.setLanguage(Locale.ENGLISH);
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);
}
}
}
});

btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mSpeech.speak(mEditText.getText().toString(),
TextToSpeech.QUEUE_FLUSH, null);
}
});

}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (mSpeech != null) {
mSpeech.stop();
mSpeech.shutdown();
}
super.onDestroy();
}
}

代码简单明了,不做过多介绍。

源码下载:语音朗读
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: