java实现文本转语音(即语音朗读)

java实现文本转语音(即语音朗读)

1.方式一:使用jacob离线语音合成

1.下载jacob-1.18.zip

链接:https://pan.baidu.com/s/1-zYB9I4VF5cPuj3ok1WLyg
提取码:7t1g

2.将 jacob-1.18-x64.dll拷贝到jdk的bin目录或windows/SysWOW64目录中

3.添加需要的依赖

 <!-- https://mvnrepository.com/artifact/com.jacob/jacob 文字转语音 -->
        <dependency>
            <groupId>com.hynnet</groupId>
            <artifactId>jacob</artifactId>
            <version>1.18</version>
        </dependency>

核心代码

package speechrecognition.demo.lianxi;

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

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * 离线 本地 TXT文件 语音朗读,生成mp3文件
 */
public class VoiceReading {
    public static void main(String[] args) {
        //本地TXT文件位置
        String text = textToStr("D:\\workspace3/1111.txt");
        textToSpeechIO(text);
    }
            

        /**
         * 字符串文本转 wav格式 语音文件
         * @param text 要读的文字字符串
         */
        public static void textToSpeechIO(String text){
             String path = "D:\\workspace3\\test/";

            ActiveXComponent ax = null;
            Dispatch spFileStream = null;
            Dispatch spAudioFormat = null;
            Dispatch spVoice = null;
            try{
                ax = new ActiveXComponent("Sapi.SpFileStream");
                spFileStream = ax.getObject();

                ax = new ActiveXComponent("Sapi.SpAudioFormat");
                spAudioFormat = ax.getObject();

                spVoice = new ActiveXComponent("Sapi.SpVoice").getObject();
                // 设置音频流格式
                Dispatch.put(spAudioFormat, "Type", new Variant(22));
                // 设置文件输出流格式
                Dispatch.putRef(spFileStream, "Format", spAudioFormat);
                //随机uuid
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
//                String filePath = path + uuid + ".wav";
                String filePath = path + uuid + ".mp3";

                // 调用输出 文件流打开方法,创建一个.wav文件
//                Dispatch.call(spFileStream, "Open", new Variant("D:\\workspace3\\test/test.mp3"), new Variant(3), new Variant(true));
                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(1));

                Dispatch.call(spVoice, "Speak", new Variant(text));

                System.out.println("输出语音文件成功!");
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                // 关闭输出文件
                Dispatch.call(Objects.requireNonNull(spFileStream), "Close");
                Dispatch.putRef(Objects.requireNonNull(spVoice), "AudioOutputStream", null);

                Objects.requireNonNull(spAudioFormat).safeRelease();
                spFileStream.safeRelease();
                spVoice.safeRelease();
                ax.safeRelease();
            }
        }

        /**
         * txt文件转字符串
         * @param fileName txt文件所在位置
         * @return txt文件中的字符串
         */
        public static String textToStr(String fileName){
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(fileName));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line=reader.readLine()) != null){
                    sb.append(line);
                }
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }finally {
                try {
                    Objects.requireNonNull(reader).close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
    /**
         * 字符串文本阅读
         * @param str 要读的文字字符串
         */
        public static void readStr(String str){
            ActiveXComponent ax = new ActiveXComponent("Sapi.SpVoice");
            //运行时输出语音内容
            Dispatch spVoice = ax.getObject();
            //设置音量 0 ~ 100
            ax.setProperty("Volume",new Variant(100));
            //设置朗读速度 -10 ~ +10
            ax.setProperty("Rate",new Variant(1));
            //执行朗读
            Dispatch.call(spVoice,"Speak",new Variant(str));
        }


}

image-20230706161811075

2.方式二:百度AI在线语音合成

添加需要的依赖

<!--百度语音播报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>

核心代码

package speechrecognition.demo.lianxi;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import org.json.JSONObject;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;
/**
 * 百度AI 语音朗读练习
 */
public class BaiDuAIDemo {
    //设置设置APPID/AK/SK
    //自己注册一个百度AI账号,在语音技术中,创建一个文档,会有一下三个参数,填上即可
    public static final String APP_ID = "";
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";

    public static void main(String[] args) {
        String text = textToStr("D:\\workspace3/2222.txt");
        synthesis(text);
//        synthesis("阳光正好,微风不燥,人间值得,未来可期!111");
    }

    /**
     * 字符串文本转 wav 或者 mp3格式 语音文件
     * @param str 要读的文字字符串
     */
    public static void synthesis(String str){
        //获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Date date = new Date();
        String fileName = sdf.format(date);
        String path = "D:\\workspace3\\test/";
        //随机uuid
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        String filePath =path + fileName + uuid + ".mp3";

        AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
        // 可选:设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选:设置代理服务器地址, http和socket二选一,或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选:设置log4j日志输出格式,若不设置,则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");
        // 设置可选参数
        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", "1");//发音人选择, 0为女声,1为男声,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女 非必选
        TtsResponse res = client.synthesis(str, "zh", 1, options);
        JSONObject result = res.getResult();    //服务器返回的内容,合成成功时为null,失败时包含error_no等信息
        if (!StringUtils.isEmpty(result)) {
            System.out.printf("error:" + result.toString());
            return;
        }
        byte[] data = res.getData();            //生成的音频数据
        JSONObject res1 = res.getResult();
        if (data != null) {
            try {
                //如果转换成功,输出的地址
                Util.writeBytesToFileSystem(data, filePath);
                System.out.println("输出语音文件成功! ");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (res1 != null) {
            System.out.println(res1.toString(2));
        }

    }


    /**
     * txt文件转字符串
     * @param fileName txt文件所在位置
     * @return txt文件中的字符串
     */
    public static String textToStr(String fileName){
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(fileName));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line=reader.readLine()) != null){
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }finally {
            try {
                Objects.requireNonNull(reader).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

posted @ 2023-07-06 16:24  爲誰心殇  阅读(783)  评论(0编辑  收藏  举报
>