Java實現語音朗讀

jacob jar包及API下載:https://download.csdn.net/download/hjinping/10391308

1、64位操作系統的將jacob-1.17-M2-x64.dll添加到JDK的bin目錄和Windows的system32目錄(32位選擇對應的dll文件,加入到對應目錄下面)

2、將jar包加入到項目中

3、編碼實現:

demo:

package com.jeeplus.common.utils;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
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 TalkUtil {
    public static void main(String[] args) throws Exception {
        talkString("你好,很高興認識你。");
        // talkText("C:/aa.txt");


    }


    public static void talkString(String talk) {
        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(talk));
            // 關閉執行對象
            sapo.safeRelease();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 關閉應用程序連接
            sap.safeRelease();
        }
    }


    public static void talkText(String path) throws Exception {
        ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
        // 輸入文件
        File srcFile = new File(path);
        // 使用包裝字符流讀取文件
        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(-1));
            // 獲取執行對象
            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();
        }
    }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章