常见的系统需求需要对文字做音频转换处理,liunx上不支持jacob,Jacob是一个针对Windows平台,本篇文章就是简单的做个示例说明下,用到的工具包依赖为:
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>jacob</artifactId>
<version>1.18</version>
</dependency>
文件 jacob-1.18-x64.dll 需放入jre/bin 中,
public static String textToSpeech(String text){
ActiveXComponent component = new ActiveXComponent("Sapi.SpVoice");
Dispatch dispatch = component.getObject();
String audioUrl = "";
Dispatch fileStreamDispatch=null;
Dispatch audioDispatch=null;
try {
// 生成空的语音文件
component = new ActiveXComponent("Sapi.SpFileStream");
fileStreamDispatch = component.getObject();
// 音频
component = new ActiveXComponent("Sapi.SpAudioFormat");
audioDispatch = component.getObject();
// 设置文件流格式
Dispatch.putRef(fileStreamDispatch, "Format", audioDispatch);
// 设置视频输出流的格式
Dispatch.put(audioDispatch, "Type", new Variant(22));
//自动生成 音频存储的位置及文件名称
String autoPath = "D:3333";
//拼接文件 类型
audioUrl = autoPath +".mp3";
// 调用输出流打开方法,创建一个.wav .mp3 .mp4 .wma文件
Dispatch.call(fileStreamDispatch,"Open",new Variant(audioUrl),new Variant(3),new Variant(true));
// 设置声音对象的音频流输出流为输出文件对象
Dispatch.putRef(dispatch,"AudioOutputStream",fileStreamDispatch);
// 设置音量大小
Dispatch.put(dispatch,"Volume",new Variant(100));
// 将文本读取进去
Dispatch.call(dispatch, "Speak",new Variant(text));
}catch (Exception e){
e.printStackTrace();
}finally {
// 关闭输出文件流
Dispatch.call(fileStreamDispatch,"Close");
Dispatch.putRef(dispatch,"AudioOutputStream",null);
audioDispatch.safeRelease();
fileStreamDispatch.safeRelease();
dispatch.safeRelease();
component.safeRelease();
}
return audioUrl;
}
直接使用即可