1.引入maven依赖


com.hynnet
jacob
1.18

2.github下载语音包插件

https://github.com/freemansoft/jacob-project/releases/tag/Root_B-1_18

3.将 jacob-1.18-x64.dll文件放到 jdk路径->jre->bin目录下

4.代码示例

  1. package cn.space.backend.server.api;
  2. import com.jacob.activeX.ActiveXComponent;
  3. import com.jacob.com.Dispatch;
  4. import com.jacob.com.Variant;
  5. /**
  6. * @Description 语音播报工具类
  7. * @Author Mike
  8. * @Version V1.3.X
  9. */
  10. public class Test {
  11. /**
  12. * 文字转语音播放
  13. *
  14. * @param text
  15. */
  16. public static void textToSpeech(String text) {
  17. ActiveXComponent ax = null;
  18. try {
  19. ax = new ActiveXComponent("Sapi.SpVoice");
  20. // 运行时输出语音内容
  21. Dispatch spVoice = ax.getObject();
  22. // 音量 0-100
  23. ax.setProperty("Volume", new Variant(100));
  24. // 语音朗读速度 -10 到 +10
  25. ax.setProperty("Rate", new Variant(-2));
  26. // 执行朗读
  27. Dispatch.call(spVoice, "Speak", new Variant(text));
  28. // 下面是构建文件流把生成语音文件
  29. ax = new ActiveXComponent("Sapi.SpFileStream");
  30. Dispatch spFileStream = ax.getObject();
  31. ax = new ActiveXComponent("Sapi.SpAudioFormat");
  32. Dispatch spAudioFormat = ax.getObject();
  33. // 设置音频流格式
  34. Dispatch.put(spAudioFormat, "Type", new Variant(22));
  35. // 设置文件输出流格式
  36. Dispatch.putRef(spFileStream, "Format", spAudioFormat);
  37. // 调用输出 文件流打开方法,创建一个.wav文件
  38. Dispatch.call(spFileStream, "Open", new Variant("./text.wav"), new Variant(3), new Variant(true));
  39. // 设置声音对象的音频输出流为输出文件对象
  40. Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
  41. // 设置音量 0到100
  42. Dispatch.put(spVoice, "Volume", new Variant(100));
  43. // 设置朗读速度
  44. Dispatch.put(spVoice, "Rate", new Variant(-2));
  45. // 开始朗读
  46. Dispatch.call(spVoice, "Speak", new Variant(text));
  47. // 关闭输出文件
  48. Dispatch.call(spFileStream, "Close");
  49. Dispatch.putRef(spVoice, "AudioOutputStream", null);
  50. spAudioFormat.safeRelease();
  51. spFileStream.safeRelease();
  52. spVoice.safeRelease();
  53. ax.safeRelease();
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. public static void main(String[] args) {
  59. Test.textToSpeech("帅的一逼");
  60. }
  61. }