Android 系统里内置了PicoTTS,对中文的支持很不给力。但是我们可以安装“讯飞语记”TTS,中文就不是问题了。
首先介绍下核心方法speak()及其参数
public int speak(final String text, final int queueMode, final HashMap<String, String> params) { return runAction(new Action<Integer>()
text 需要转成语音的文字
queueMode 队列方式:
QUEUE_ADD:播放完之前的语音任务后才播报本次内容
QUEUE_FLUSH:丢弃之前的播报任务,立即播报本次内容
params 设置TTS参数,可以是null。
KEY_PARAM_STREAM:音频通道,可以是:STREAM_MUSIC、STREAM_NOTIFICATION、STREAM_RING等
KEY_PARAM_VOLUME:音量大小,0-1f
返回值:int SUCCESS = 0,int ERROR = -1。
以下是Demo代码
package com.interjoy.demoqrcode;import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;import java.util.Locale;public class MainActivity extends AppCompatActivity {private Button btn_to_speak;private TextToSpeech mSpeech;private EditText et_input;private static final String TAG_TTS = "MainActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}private <T> T f(int resId) {return (T) findViewById(resId);}private void init() {btn_to_speak = f(R.id.btn_to_speak);et_input = f(R.id.et_input);speechInit();btn_to_speak.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String text = et_input.getText().toString();if (TextUtils.isEmpty(text)) text = "请输入要测试的内容";playTTS(text);}});}/*** 初始化TextToSpeech,在onCreate中调用*/private void speechInit() {if (mSpeech != null) {mSpeech.stop();mSpeech.shutdown();mSpeech = null;}// 创建TTS对象mSpeech = new TextToSpeech(MainActivity.this, new TTSListener());}/*** 将文本用TTS播放** @param str 播放的文本内容*/private void playTTS(String str) {if (mSpeech == null) mSpeech = new TextToSpeech(this, new TTSListener());mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);Log.i(TAG_TTS, "播放语音为:" + str);}private final class TTSListener implements TextToSpeech.OnInitListener {@Overridepublic void onInit(int status) {Log.e(TAG_TTS, "初始化结果:" + (status == TextToSpeech.SUCCESS));int result = mSpeech.setLanguage(Locale.CHINESE);//如果返回值为-2,说明不支持这种语言Log.e(TAG_TTS, "是否支持该语言:" + (result != TextToSpeech.LANG_NOT_SUPPORTED));}}@Overrideprotected void onDestroy() {if (mSpeech != null) {mSpeech.stop();mSpeech.shutdown();mSpeech = null;}super.onDestroy();}
}
注意:1.安装讯飞语记之后,需要设置为把它设置为默认TTS,就像安装搜狗输入法后要设置手机输入法默认为搜狗才能用一样。我使用华为荣耀5A具体设置步骤:设置->辅助功能->文字转语音(TTS)输出->讯飞语记
2.不用时需要及时关闭释放tts对象 mSpeech.shutdown();