1.实现过程
通过前端传过来的一段文字,将其转成一段音频文件上传到服务器,然后将这个音频文件的路径传给前端,前端进行播放就可以实现该功能
2.第三方依赖
<!-- https://mvnrepository.com/artifact/com.jacob/jacob 文字转语音 -->
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>jacob</artifactId>
<version>1.18</version>
</dependency>
3.linux服务器代码,书写http接口,调用windows服务器上的转语音代码
//text要转成语音的文字
public static String readTextByWindows(String text) {
JSONObject params = new JSONObject();
params.put("text",text);
//CommonConstants.readTextIP是调用windows服务器代码的ip地址
String url=CommonConstants.readTextIP+"read/readText";
Header[] headers = {
new BasicHeader("Content-Type", "application/json; charset=UTF-8")
};
JSONObject jsonObject = WebClientService.doPostQueryToJson(url, headers, params.toJSONString());
return jsonObject.toJSONString();
}
4.windows服务器代码,通过上边传过来的文字,转成语音保存到指定的路径,同时把保存后的文件路径个名字返回
/**
* 语音转文字并播放
*
* @param text
*/
public static JSONObject textToSpeech(JSONObject text1) {
String text =(String) text1.get("text");
//语音名字
String name="wav" + UUID.randomUUID().toString() + ".wav";
//语音访问路径
String wavName = Common.saveAudioPath + name;
//语音保存路径
//String wavName = "/upload/task/audios/" + "wav" + UUID.randomUUID().toString() + ".wav";
ActiveXComponent ax = null;
JSONObject jsonObject = new JSONObject();
jsonObject.put("code",0);
try {
ax = new ActiveXComponent("Sapi.SpVoice");
// 运行时输出语音内容
Dispatch spVoice = ax.getObject();
// 音量 0-100
ax.setProperty("Volume", new Variant(100));
// 语音朗读速度 -10 到 +10
ax.setProperty("Rate", new Variant(-2));
// 执行朗读
//Dispatch.call(spVoice, "Speak", new Variant(text));
// 下面是构建文件流把生成语音文件
ax = new ActiveXComponent("Sapi.SpFileStream");
Dispatch spFileStream = ax.getObject();
ax = new ActiveXComponent("Sapi.SpAudioFormat");
Dispatch spAudioFormat = ax.getObject();
// 设置音频流格式
Dispatch.put(spAudioFormat, "Type", new Variant(22));
// 设置文件输出流格式
Dispatch.putRef(spFileStream, "Format", spAudioFormat);
// 调用输出 文件流打开方法,创建一个.wav文件
Dispatch.call(spFileStream, "Open", new Variant(wavName), new Variant(3), new Variant(true));
// 设置声音对象的音频输出流为输出文件对象
Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
// 设置音量 0到100
Dispatch.put(spVoice, "Volume", new Variant(100));
// 设置朗读速度
Dispatch.put(spVoice, "Rate", new Variant(-2));
// 开始朗读
Dispatch.call(spVoice, "Speak", new Variant(text));
// 关闭输出文件
Dispatch.call(spFileStream, "Close");
Dispatch.putRef(spVoice, "AudioOutputStream", null);
spAudioFormat.safeRelease();
spFileStream.safeRelease();
spVoice.safeRelease();
ax.safeRelease();
} catch (Exception e) {
e.printStackTrace();
jsonObject.put("code",404);
jsonObject.put("msg","找不到该路径");
}
jsonObject.put("wavName",Common.audioVisitPath+name);
return jsonObject;
}
5.dll文件
这边还需要一个dll文件,而且该文件只能部署在windows服务器里,部署方式和文件小编已经放到百度网盘了,链接:https://pan.baidu.com/s/1A64iFCsSOWWaJyeo3ixyHw
提取码:if4q
6.补充,
很多人很迷惑为什么一个文字转语音代码会用到两个不同的服务器,还要去调用,这个问题是避免不了的,因为这个dll文件只能在windows服务器运行,小编会在下一篇给大家解惑