溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在java中調(diào)用本地揚聲器

發(fā)布時間:2021-05-14 16:30:23 來源:億速云 閱讀:154 作者:Leah 欄目:開發(fā)技術

怎么在java中調(diào)用本地揚聲器?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

1.首先,我們需要一個dll作為輔助。這里解釋一下dll的含義(DLL(Dynamic Link Library)文件為動態(tài)鏈接庫文件,又稱“應用百程序拓展”,是軟件文件類型。在Windows中,許多應用程序并不是一個度完整的可執(zhí)行文件,它們被分割成一些相知對獨立的動態(tài)鏈接庫,即DLL文件,放置于道系統(tǒng)中。當我們執(zhí)行某一個程序時,相應的版DLL文件就會被調(diào)用。一個應用程序可使用權(quán)多個DLL文件,一個DLL文件也可能被不同的應用程序使用,這樣的DLL文件被稱為共享DLL文件)。

需要把jacob-1.17-M2-x64.dll復制到C:\Windows\System32\目錄下。我們也能看到目錄下有很多的.dll文件。

這里的文件大家自己百度下,很好找的。

2.使用maven項目導入坐標。

<!-- https://mvnrepository.com/artifact/net.sf.jacob-project/jacob -->
<dependency>
	<groupId>net.sf.jacob-project</groupId>
	<artifactId>jacob</artifactId>
	<version>1.14.3</version>
</dependency>

3.測試類代碼。

/**
 * 文字轉(zhuǎn)語音測試 jdk bin文件中需要導入jacob-1.17-M2-x64.dll
 * 注意導包哈
 */
public class Jacobtest {


    public static void main(String[] args) {
        textToSpeech("工作人員請注意,桌號8001顧客正在尋求幫助?。?quot;);
    }

    /**
     * 語音轉(zhuǎn)文字并播放
     *
     * @param text
     */
    public static void textToSpeech(String text) {
        ActiveXComponent ax = null;
        try {
            ax = new ActiveXComponent("Sapi.SpVoice");

            // 運行時輸出語音內(nèi)容
            Dispatch spVoice = ax.getObject();
            // 音量 0-100
            ax.setProperty("Volume", new Variant(100));
            // 語音朗讀速度 -10 到 +10
            ax.setProperty("Rate", new Variant(0));
            // 執(zhí)行朗讀
            Dispatch.call(spVoice, "Speak", new Variant(text));

           /* // 下面是構(gòu)建文件流把生成語音文件

            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);
            // 調(diào)用輸出 文件流打開方法,創(chuàng)建一個.wav文件
            Dispatch.call(spFileStream, "Open", new Variant("./text.wav"), new Variant(3), new Variant(true));
            // 設置聲音對象的音頻輸出流為輸出文件對象
            Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
            // 設置音量 0到100
            Dispatch.put(spVoice, "Volume", new Variant(100));
            // 設置朗讀速度
            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();
        }
    }
}

4.從測試類可以看出,這個方法既可以發(fā)聲還能輸出后綴為.wav的文件,這是一個標準的多媒體文件。上述代碼注釋很清晰,就不解釋了,自己看哈。

5.測試成功,現(xiàn)在集成到自己的項目中。

另述

這里說到了調(diào)用揚聲器發(fā)聲,不放還可以想一下如何調(diào)用麥克風收音。

public class EngineeCore {
    String filePath = "E:\\voice\\voice_cache.wav";
    AudioFormat audioFormat;
    TargetDataLine targetDataLine;
    boolean flag = true;
    
	private void stopRecognize() {
        flag = false;
        targetDataLine.stop();
        targetDataLine.close();
    }
    private AudioFormat getAudioFormat() {
        float sampleRate = 16000;
        // 8000,11025,16000,22050,44100
        int sampleSizeInBits = 16;
        // 8,16
        int channels = 1;
        // 1,2
        boolean signed = true;
        // true,false
        boolean bigEndian = false;
        // true,false
        return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
    }// end getAudioFormat


    private void startRecognize() {
        try {
            // 獲得指定的音頻格式
            audioFormat = getAudioFormat();
            DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
            targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
            // Create a thread to capture the microphone
            // data into an audio file and start the
            // thread running. It will run until the
            // Stop button is clicked. This method
            // will return after starting the thread.
            flag = true;
            new CaptureThread().start();
        } catch (Exception e) {
            e.printStackTrace();
        } // end catch
    }// end captureAudio method

    class CaptureThread extends Thread {
        public void run() {
            AudioFileFormat.Type fileType = null;
            File audioFile = new File(filePath);

            fileType = AudioFileFormat.Type.WAVE;
            //聲音錄入的權(quán)值
            int weight = 2;
            //判斷是否停止的計數(shù)
            int downSum = 0;

            ByteArrayInputStream bais = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            AudioInputStream ais = null;
            try {
                targetDataLine.open(audioFormat);
                targetDataLine.start();
                byte[] fragment = new byte[1024];

                ais = new AudioInputStream(targetDataLine);
                while (flag) {

                    targetDataLine.read(fragment, 0, fragment.length);
                    //當數(shù)組末位大于weight時開始存儲字節(jié)(有聲音傳入),一旦開始不再需要判斷末位
                    if (Math.abs(fragment[fragment.length-1]) > weight || baos.size() > 0) {
                        baos.write(fragment);
                        System.out.println("守衛(wèi):"+fragment[0]+",末尾:"+fragment[fragment.length-1]+",lenght"+fragment.length);
                        //判斷語音是否停止
                        if(Math.abs(fragment[fragment.length-1])<=weight){
                            downSum++;
                        }else{
                            System.out.println("重置奇數(shù)");
                            downSum=0;
                        }
               //計數(shù)超過20說明此段時間沒有聲音傳入(值也可更改)
                        if(downSum>20){
                            System.out.println("停止錄入");
                            break;
                        }

                    }
                }

                //取得錄音輸入流
                audioFormat = getAudioFormat();
                byte audioData[] = baos.toByteArray();
                bais = new ByteArrayInputStream(audioData);
                ais = new AudioInputStream(bais, audioFormat, audioData.length / audioFormat.getFrameSize());
                //定義最終保存的文件名
                System.out.println("開始生成語音文件");
                AudioSystem.write(ais, AudioFileFormat.Type.WAVE, audioFile);
                downSum = 0;
                stopRecognize();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //關閉流

                try {
                    ais.close();
                    bais.close();
                    baos.reset();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }// end run
    }// end inner class CaptureThread

Java是什么

Java是一門面向?qū)ο缶幊陶Z言,可以編寫桌面應用程序、Web應用程序、分布式系統(tǒng)和嵌入式系統(tǒng)應用程序。

關于怎么在java中調(diào)用本地揚聲器問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI