1. 程式人生 > 其它 >jacob 進行文字轉語音,並輸出語音

jacob 進行文字轉語音,並輸出語音

參考:https://www.meihaocloud.com/1060.html

package test1;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class JacobTest {

    /**
     *  將文字直接朗讀
     * @param text
     */
    public static void textToSpeech(String text) {
        ActiveXComponent ax 
= null; try { ax = new ActiveXComponent("Sapi.SpVoice"); // 執行時輸出語音內容 Dispatch spVoice = ax.getObject(); // 音量 0-100 ax.setProperty("Volume", new Variant(100)); // 語音朗讀速度 -10 到 +10 ax.setProperty("Rate", new Variant(2));
// 執行朗讀 Dispatch.call(spVoice, "Speak", new Variant(text)); spVoice.safeRelease(); ax.safeRelease(); } catch (Exception e) { e.printStackTrace(); } } /** * 將文字儲存為音訊檔案 wav、mp3 * @param text * @param filePath */ public
static void textToAudio(String text, String filePath) { ActiveXComponent ax = null; try { ax = new ActiveXComponent("Sapi.SpVoice"); // 執行時輸出語音內容 Dispatch spVoice = ax.getObject(); // 音量 0-100 ax.setProperty("Volume", new Variant(100)); // 語音朗讀速度 -10 到 +10 ax.setProperty("Rate", new Variant(2)); // 將檔案流把生成音訊檔案 ax = new ActiveXComponent("Sapi.SpFileStream"); Dispatch spFileStream = ax.getObject(); ax = new ActiveXComponent("Sapi.SpAudioFormat"); Dispatch spAudioFormat = ax.getObject(); // 設定音訊流格式 Dispatch.put(spAudioFormat, "Type", new Variant(22)); // 設定檔案輸出流格式 Dispatch.putRef(spFileStream, "Format", spAudioFormat); // 呼叫輸出 檔案流開啟方法,建立一個.wav .mp3檔案 Dispatch.call(spFileStream, "Open", new Variant(filePath), new Variant(3), new Variant(true)); // 設定聲音物件的音訊輸出流為輸出檔案物件 Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream); // 設定音量 0到100 Dispatch.put(spVoice, "Volume", new Variant(100)); // 設定朗讀速度 -10 到 +10 Dispatch.put(spVoice, "Rate", new Variant(2)); // 開始朗讀 Dispatch.call(spVoice, "Speak", new Variant(text)); // 關閉輸出檔案 Dispatch.call(spFileStream, "Close"); Dispatch.putRef(spVoice, "AudioOutputStream", null); spAudioFormat.safeRelease(); spFileStream.safeRelease(); spVoice.safeRelease(); ax.safeRelease(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String str = "12日公佈的“十四五”規劃和2035年遠景目標綱要明確提出,按照“小步調整、彈性實施、分類推進、統籌兼顧”等原則,逐步延遲法定退休年齡。"; // 直接朗讀 textToSpeech(str); // 生成檔案 textToAudio(str, "d://test.mp3"); } }
View Code

下載:https://github.com/freemansoft/jacob-project/releases

報錯:no jacob-1.20-x64 in java.library.path

將jacob-1.20-x64.dll或者jacob-1.20-x86.dll放到  /jre/bin下