概念
介绍:TextToSpeech将一段文字转换为语音。TextToSpeech是Android系统自带的类,不用导入别的包。
语言:英文Ok,不支持中文
步骤:
- new TextToSpeech类
- 初始化TextToSpeech引擎,即重写onInit()方法
- 设置朗读参数,调用朗读方法speak()
- 销毁TextToSpeech,调用stop()和shutdown()方法
接口实现代码
//1.实现接口
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private EditText et_voice_content;
private Button btn_play;
//TextToSpeech类
private TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_voice_content = (EditText) findViewById(R.id.et_voice_content);
btn_play = (Button) findViewById(R.id.btn_play);
//2.创建对象:参数1(Context),参数2(TextToSpeech.OnInitListener)
tts = new TextToSpeech(this, this);
btn_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//3.设置朗读参数
//设置音调,值越大声音越尖(女生),值越小则变为男生,1.0位常规
tts.setPitch(1.0f);
//设置语速
tts.setSpeechRate(0.3f);
if (et_voice_content.getText().length() >= 1) {
//4.开始朗读
tts.speak(et_voice_content.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
} else {
Toast.makeText(MainActivity.this,"内容为空", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* 5.初始化TextToSpeech引擎
* status:SUCCESS或ERROR这2个值
* setLanguage设置语言,帮助文档里面写了有22种
* TextToSpeech.LANG_MISSING_DATA:表示语言的数据丢失。
* TextToSpeech.LANG_NOT_SUPPORTED:表示语音不支持
* LANG_COUNTRY_AVAILABLE 1 表示本地语音或者方言可用,引申语音不可用
*/
@Override
public void onInit(int status) {
if (status == tts.SUCCESS) {
//设置使用美式英语朗读
int result1 = tts.setLanguage(Locale.US);
//设置支持中文,但实现不了
//int result2 = tts.setLanguage(Locale.CHINESE);
if (result1 == TextToSpeech.LANG_MISSING_DATA|| result1==TextToSpeech.LANG_NOT_SUPPORTED)
{
Toast.makeText(this, "数据丢失或不支持:"+result1+";", Toast.LENGTH_SHORT).show();
}
}
}
/**
* 6.关闭tts
*/
@Override
protected void onDestroy() {
super.onDestroy();
if (tts != null) {
//停止
tts.stop();
//关闭
tts.shutdown();
}
}
}
匿名内部类实现
textToSpeech= new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status==textToSpeech.SUCCESS)
{
int result=textToSpeech.setLanguage(Locale.US);
if(result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED)
{
Toast.makeText(MainActivity.this, "onInit failure", Toast.LENGTH_LONG).show();
}
}
}
});