您的位置:首页 > 其它

使用TextToSpeech实现文本转音频(自动朗读)

2015-04-08 21:12 471 查看
主要方法

setLanguage:设置语言的类型

speak:传入文本播放声音

synthesizeToFile:传入文本保存为音频

shutdown:释放TextToSpeech资源

package prictise.lxm.prictise;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Locale;

/**
* 使用TextToSpeech实现自动朗读
*/
public class MainActivity extends Activity{

TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//获取界面视图
final EditText edTxtSpeak = (EditText)findViewById(R.id.edTxt_speak);
final Button btnSpeak = (Button)findViewById(R.id.btn_speak);
final Button btnSave = (Button)findViewById(R.id.btn_save);

textToSpeech = new TextToSpeech(this,new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
//初始化成功,设置语言
if(status == TextToSpeech.SUCCESS){
//设置语言为美式英语
int result = textToSpeech.setLanguage(Locale.US);
//设置语言为中文
// int result = textToSpeech.setLanguage(Locale.CHINA);
if(result != TextToSpeech.LANG_AVAILABLE &&
result != TextToSpeech.LANG_COUNTRY_AVAILABLE){ //不支持当前语言
Toast.makeText(MainActivity.this,"不支持" + textToSpeech.getLanguage().
getDisplayName(),Toast.LENGTH_SHORT).show();
//设置发音按钮不可用
btnSave.setEnabled(false);
btnSpeak.setEnabled(false);
}
}
}
});

//播放按钮
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textToSpeech.speak(edTxtSpeak.getText().toString(),TextToSpeech.QUEUE_ADD,null);
}
});

btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textToSpeech.synthesizeToFile(edTxtSpeak.getText().toString(),null,"speakUs");
}
});
}

protected void onDestroy() {
//释放tts
if(textToSpeech != null) {
textToSpeech.shutdown();
}
super.onDestroy();
}

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