Android中TextToSpeech的简单使用

本文介绍如何在Android应用中使用TextToSpeech API将输入的文字转换为语音朗读出来,提供了完整的示例代码,并说明了目前支持的语言种类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android也可以实现把输入的文字朗读出来,使用到的是TextToSpeech,不过目前只支持5种语言:English French  German  Italian  Spanish。(真遗憾,没有Chinese),对android系统要求为android 1.6(API8)以上:

public class SpeechTestActivity extends Activity {

/**TextToSpeech对象*/
private TextToSpeech mText2Speech;
/**确定按钮*/
private Button mBtn;
/**文本输入框*/
private EditText mEdt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
initListeners();
mBtn = (Button) findViewById(R.id.test_btn);
mEdt = (EditText) findViewById(R.id.test_edt);
mBtn.setEnabled(false);


}


private void initListeners() {
mText2Speech = new TextToSpeech(this, new OnInitListener() {

@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {/**如果装载TTS成功*/
int result = mText2Speech.setLanguage(Locale.ENGLISH);/**有Locale.CHINESE,但是不支持中文*/
if (result == TextToSpeech.LANG_MISSING_DATA/**表示语言的数据丢失。*/
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {/**语言不支持*/
Toast.makeText(SpeechTestActivity.this, "我说不出口", Toast.LENGTH_SHORT).show();
} else {
mBtn.setEnabled(true);
mText2Speech.speak("I miss you", TextToSpeech.QUEUE_FLUSH,
null);
}
}
}
});

mBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
mText2Speech.speak(mEdt.getText().toString(),
TextToSpeech.QUEUE_FLUSH, null);
}
});
}


private void findViewsById() {
mBtn = (Button) findViewById(R.id.test_btn);
mEdt = (EditText) findViewById(R.id.test_edt);
}


@Override
protected void onDestroy() {
if (mText2Speech != null) {
mText2Speech.stop();
mText2Speech.shutdown();
}
super.onDestroy();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值