22、TTS技术

时间:2023-03-10 04:59:02
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
 import java.util.Locale;

 import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast; @SuppressLint("NewApi") /**
* 朗读文本
*
* 安卓本身的库,只支持英文。除非从网上更新下载其他语言包。
* @author dr
*/
public class Main extends Activity implements TextToSpeech.OnInitListener,
OnClickListener {
private TextToSpeech tts;
private TextView textView; @SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); tts = new TextToSpeech(this, this); Button button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textview);
button.setOnClickListener(this);
} public void onClick(View view) {
tts.speak(textView.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
} @Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(this, "Language is not available.",
Toast.LENGTH_LONG).show();
}
} } }