使用java实现语音播报

转载:https://blog.csdn.net/xichengqc/article/details/78709724


准备工作:

下载jar包,链接:https://pan.baidu.com/s/1qXPgCzy 密码:xigv

解压jar包,将jacob.jar复制到工程目录,右键该文件→Build Path→Add to...

将jacob-1.17-M2-x86.dll添加到JDK的bin目录和Windows的system32目录(64位系统添加jacob-1.17-M2-x64.dll

代码实现如下:

  1. import com.jacob.activeX.ActiveXComponent;
  2. import com.jacob.com.Dispatch;
  3. import com.jacob.com.Variant;
  4. public class Test04 {
  5. public static void main(String[] args) {
  6. ActiveXComponent sap = new ActiveXComponent( "Sapi.SpVoice");
  7. try {
  8. // 音量 0-100
  9. sap.setProperty( "Volume", new Variant( 100));
  10. // 语音朗读速度 -10 到 +10
  11. sap.setProperty( "Rate", new Variant(- 2));
  12. // 获取执行对象
  13. Dispatch sapo = sap.getObject();
  14. // 执行朗读
  15. Dispatch.call(sapo, "Speak", new Variant( "你好,很高兴见到你。"));
  16. // 关闭执行对象
  17. sapo.safeRelease();
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. } finally {
  21. // 关闭应用程序连接
  22. sap.safeRelease();
  23. }
  24. }
  25. }
进一步,我们可以朗读文件内容,代码实现如下:
  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import com.jacob.activeX.ActiveXComponent;
  6. import com.jacob.com.Dispatch;
  7. import com.jacob.com.Variant;
  8. public class Test05 {
  9. public static void main(String[] args) throws IOException {
  10. ActiveXComponent sap = new ActiveXComponent( "Sapi.SpVoice");
  11. //输入文件
  12. File srcFile = new File( "E:/tmp/testvoice.txt");
  13. //使用包装字符流读取文件
  14. BufferedReader br = new BufferedReader( new FileReader(srcFile));
  15. String content = br.readLine();
  16. try {
  17. // 音量 0-100
  18. sap.setProperty( "Volume", new Variant( 100));
  19. // 语音朗读速度 -10 到 +10
  20. sap.setProperty( "Rate", new Variant(- 2));
  21. // 获取执行对象
  22. Dispatch sapo = sap.getObject();
  23. // 执行朗读
  24. while (content != null) {
  25. Dispatch.call(sapo, "Speak", new Variant(content));
  26. content = br.readLine();
  27. }
  28. // 关闭执行对象
  29. sapo.safeRelease();
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. } finally {
  33. br.close();
  34. // 关闭应用程序连接
  35. sap.safeRelease();
  36. }
  37. }
  38. }

代码分析:具体代码实现如上,代码内容本人也不理解,后续会加更代码解释;如果文件读取过程中出现错误,请检查文件编码格式,默认读取的是UTF-8的文本内容

猜你喜欢

转载自blog.csdn.net/Yuwen_forJava/article/details/80996885
今日推荐