转载:https://blog.youkuaiyun.com/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)
代码实现如下:
- import com.jacob.activeX.ActiveXComponent;
- import com.jacob.com.Dispatch;
- import com.jacob.com.Variant;
- public class Test04 {
- public static void main(String[] args) {
- ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
- try {
- // 音量 0-100
- sap.setProperty("Volume", new Variant(100));
- // 语音朗读速度 -10 到 +10
- sap.setProperty("Rate", new Variant(-2));
- // 获取执行对象
- Dispatch sapo = sap.getObject();
- // 执行朗读
- Dispatch.call(sapo, "Speak", new Variant("你好,很高兴见到你。"));
- // 关闭执行对象
- sapo.safeRelease();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- // 关闭应用程序连接
- sap.safeRelease();
- }
- }
- }
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- import com.jacob.activeX.ActiveXComponent;
- import com.jacob.com.Dispatch;
- import com.jacob.com.Variant;
- public class Test05 {
- public static void main(String[] args) throws IOException {
- ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
- //输入文件
- File srcFile = new File("E:/tmp/testvoice.txt");
- //使用包装字符流读取文件
- BufferedReader br = new BufferedReader(new FileReader(srcFile));
- String content = br.readLine();
- try {
- // 音量 0-100
- sap.setProperty("Volume", new Variant(100));
- // 语音朗读速度 -10 到 +10
- sap.setProperty("Rate", new Variant(-2));
- // 获取执行对象
- Dispatch sapo = sap.getObject();
- // 执行朗读
- while (content != null) {
- Dispatch.call(sapo, "Speak", new Variant(content));
- content = br.readLine();
- }
- // 关闭执行对象
- sapo.safeRelease();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- br.close();
- // 关闭应用程序连接
- sap.safeRelease();
- }
- }
- }
代码分析:具体代码实现如上,代码内容本人也不理解,后续会加更代码解释;如果文件读取过程中出现错误,请检查文件编码格式,默认读取的是UTF-8的文本内容