TextToSpeech文字转语音、文字转音频文件并播放
前段时间遇到了语音读网页的需求,特地在网上找了一些资料。学习完毕后跟大家分享一下。这里是我从项目中抽取出来的代码,大家应该也基本能看清楚流程了。上代码
首先是文字转语音及文件的工具类
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import java.io.File;
import java.util.Locale;
/**
* Created by ly on 2018/8/20.
*/
public class TTSHelper extends UtteranceProgressListener {
private TextToSpeech tts;
private boolean isSupportCN = true;
public TTSHelper(Context context) {
tts = new TextToSpeech(context, status -> {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.CHINA);
tts.setPitch(1.0f);// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
tts.setSpeechRate(1.0f);//设置语速
tts.setOnUtteranceProgressListener(TTSHelper.this);
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
isSupportCN = false;//该设备是否支持设置语音的标记
}
}
});
}
/**
*
* @param content 要转换成文件的文字内容
* @param path 音频文件地址 xxx.mp3
* @return
*/
public int textToFile(String content, File path) {
int i = tts.synthesizeToFile(content,null,path, "pensoin-record");
return i;
}
@Override
public void onStart(String utteranceId) {
Log.d("xulc", "onStart---utteranceId--->" + utteranceId);
}
@Override
public void onDone(String utteranceId) {
Log.d("xulc", "onDone---utteranceId--->" + utteranceId);
}
@Override
public void onError(String utteranceId) {
Log.d("xulc", "onError---utteranceId--->" + utteranceId);
}
public TextToSpeech getTts() {
return tts;
}
public boolean is