java簡單實現用語音讀txt文檔

  最近比較無聊,隨便翻着博客,無心中看到了有的人用VBS讀文本內容,也就是讀幾句中文,emmm,挺有趣的,實現也很簡單,都不須要安裝什麼環境,直接新建txt文件,輸入一些簡單的vbs讀文本的代碼,而後將新建的文件後綴改成.vbs,而後雙擊一下就能夠有效果了。。。。java

  因而我就想啊,java行不行呢?查了一些資料,還真的行,我就將我試驗的過程說一下,就看成娛樂娛樂!json

1.依賴api

  隨便新建一個maven項目,導入依賴服務器

<dependency>
        <groupId>com.hynnet</groupId>
        <artifactId>jacob</artifactId>
        <version>1.18</version>
</dependency>

  

  只導入依賴還不行,還要導入一個.dll文件,百度雲連接:連接:https://pan.baidu.com/s/1YYYPIoPxrtuyKebJzabhlw    提取碼:s62o ,能夠看到有兩個dll文件,因爲個人電腦是64位的,因而我將上面那個dll文件複製一份到當前使用jdk的bin目錄下網絡

 

2.java代碼實現框架

  一個很簡單的java代碼實現,運行以後就會讀出來了;maven

package com.wyq.day66;

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

public class Speak02 {
    
    //用電腦自帶的語音讀字符串str
    public static void main(String[] args) {
         String str = "你好,我是java小新人!請叫我最帥的帥鍋";
         
         ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
         Dispatch sapo = sap.getObject();
         try {
             // 音量 0-100
             sap.setProperty("Volume", new Variant(100));
             // 語音朗讀速度 -10 到 +10
             sap.setProperty("Rate", new Variant(0));
             // 執行朗讀 
              Dispatch.call(sapo, "Speak", new Variant(str));
              
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             sapo.safeRelease();
             sap.safeRelease();
         }
         
    }

}

 

3.輸出音頻文件編碼

  按理說到上面已經實現了功能,可是我還想着能不能把讀的音頻文件該輸出一下呢?查了查資料,竟然還真行,代碼以下:spa

package com.wyq.day66;

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

public class JavaSpeak {

    public static void main(String[] args) {
        //指定文件音頻輸出文件位置
        String output = "E:\\test.wav";
        
        ActiveXComponent ax = null;
        String str="我是java小新人,我要將這段話的音頻輸出一下";
        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(-3));
            // 進行朗讀
            Dispatch.call(spVoice, "Speak", new Variant(str));

            //下面是構建文件流把生成語音文件

            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文件
            Dispatch.call(spFileStream, "Open", new Variant(output), 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(str));

            //關閉輸出文件
            Dispatch.call(spFileStream, "Close");
            Dispatch.putRef(spVoice, "AudioOutputStream", null);

            spAudioFormat.safeRelease();
            spFileStream.safeRelease();
            spVoice.safeRelease();
            ax.safeRelease();

            } catch (Exception e) {
                e.printStackTrace();
            }
    
    }

}

  直接運行咱們就能夠聽到朗讀的聲音,並且在指定目錄還能夠找到音頻文件;3d

 

4.調用百度AI來讀文本

  又按理說到上面應該就差很少了,可是我老是感受電腦自帶的語音庫聲音很差聽,我要用百度AI的那個比較可愛的聲音,我仍是去查了查資料,竟然能夠,並且很容易!

  4.1.申請一下百度語音api權限

  因爲咱們是要去調用百度的api進行語音識別,那麼咱們要先去申請一下權限,否則會一直報錯(這個地方卡了很久,最後終於被我查出來爲何報錯了。。。),連接:http://ai.baidu.com/

 

  而後會讓你登陸一下,直接用qq登陸就行;

 

   建立完畢以後查看一下應用詳情:

 

  4.2.代碼實現

  作了這麼可能是操做就是爲了獲得這三個字符串,如今咱們還要導入百度語音的依賴:

<!--百度語音播報sdk-->
    <dependency>
        <groupId>com.baidu.aip</groupId>
        <artifactId>java-sdk</artifactId>
        <version>4.4.1</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20160810</version>
    </dependency>

 

  桌面上記事本中的內容:

 

 

  java代碼實現以下,其實就是利用百度AI讀取咱們計算機中的一個txt文檔,輸出MP3文件保存併到指定位置

package com.wyq.day66;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import org.json.JSONObject;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;

public class Speak03 {
    //設置APPID/AK/SK,這三個參數是須要咱們去百度AI平臺申請的(也就是上面說的那三個字符串)
    public static final String APP_ID = "16447127";
    public static final String API_KEY = "8GO31sOIffR1oll5mPFKgtR9";
    public static final String SECRET_KEY = "jWsoNGlfzfRGSQ30****NOxz9ZpjMbc";
    
    //readFile是咱們的txt文檔,writeFile是輸出的MP3格式
    public static String readFile = "C:\\Users\\asus\\Desktop\\says.txt";
    public static String writeFile = "E:\\output.mp3";


    public static void main(String[] args) {
        //能夠直接輸入字符串也行,內容比較多的話仍是用txt文檔比較好一點
        //convertMP3("你好!我是百度AI智能,java小新人,很高興和你見面,咱們必定能成爲很好的朋友的");
        
        
        //調用readToString方法將一個txt文檔中的數據讀取出來變成一個字符串
        String string = readToString(readFile);
        //將這個字符串用百度AI讀一下輸出MP3格式
        convertMP3(string);

    }
     public static void convertMP3(String str) {
            AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
            // 可選:設置網絡鏈接參數,就是超時時間
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);

            // 設置一些可選參數
            HashMap<String, Object> options = new HashMap<String, Object>();
            options.put("spd", "5");//語速,取值0-9,默認爲5中語速      非必選
            options.put("pit", "5");//音調,取值0-9,默認爲5中語調      非必選
            options.put("per", "4");//發音人選擇, 0爲女聲,1爲男聲,3爲情感合成-度逍遙,4爲情感合成-度丫丫,默認爲普通女 非必選
            
            //百度AI開始讀取傳入的str字符串
            TtsResponse res = client.synthesis(str, "zh", 1, options);
            
            //服務器返回的內容,合成成功時爲null,失敗時包含error_no等信息
            JSONObject result = res.getResult();   
            if (result != null) {
                System.out.printf("error:" + result.toString()+"----------");
                return;
            }
           //生成的音頻數據
            byte[] data = res.getData();            
            JSONObject res1 = res.getResult();
            if (data != null) {
                try {
                    //將生成的音頻輸出到指定位置
                    Util.writeBytesToFileSystem(data, writeFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if (res1 != null) {
                System.out.println(res1.toString());
            }
        }
     
     //這個方法就是根據輸入的文件路徑,讀取該文件內容返回一個很長的字符串,因爲txt是gbk編碼,因此咱們變成字符串的時候也要用gbk
     //其實就是最基本的流操做
     public static String readToString(String fileName) {  
            String encoding = "gbk";  
            File file = new File(fileName);  
            Long filelength = file.length();  
            byte[] filecontent = new byte[filelength.intValue()];  
            
            try {  
                FileInputStream in = new FileInputStream(file);  
                in.read(filecontent);  
                in.close();  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            
            try {  
                return new String(filecontent, encoding);  
            } catch (UnsupportedEncodingException e) {  
                System.err.println("The OS does not support " + encoding);  
                e.printStackTrace();  
                return null;  
            }  
        }
    

}

 

  輸出的音頻文件: 

 

5.總結

   感受仍是有點兒意思的,沒事的時候用java玩一玩這些東西就當是打發時間!老是看一些框架原理啊什麼的,時間長了也是比較無聊的,能夠挖掘一下java的其餘功能也不錯!

相關文章
相關標籤/搜索