首页 > 编程语言 >java实现文本转语音(即语音朗读)

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

时间:2023-07-06 16:35:32浏览次数:41  
标签:java String Variant Dispatch 语音 new import 朗读

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();
            }
        }
    }

}

标签:java,String,Variant,Dispatch,语音,new,import,朗读
From: https://www.cnblogs.com/yin-jihu/p/17532540.html

相关文章

  • java http大文件断点续传上传问题
    ​ 这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数下面直接贴代码吧,一些难懂的我大部分都加上注释了:上传文件实体类:看得出来,实体类中已经有很多我们需要的功能了,还有实用的属性。如MD5秒传的信息。pub......
  • 报错 Cannot construct instance of `java.time.LocalDate` LocalDateTime
    原因:报错的原因就是导入了JacksonObjectMapper对象映射器,导致不知道怎么将LocalDateTime转换成Json类型的数据了,在没有导入使用JacksonObjectMapper的时候是不会报错的。解决方式:指定LocalDateTime类型的数据如何进行序列化就好了,给实体类中LocalDateTime的属性加上注解就可以了:......
  • java中http请求-okhttp使用连接池优化
    愿历尽千帆,归来仍是少年原因:避免频繁频繁的开关连接。1.Maven添加依赖<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>3.10.0</version></dependency>2.OkHttpConfiguration配置类......
  • JAVA_DAY_01
    第一天1.jdk针对Java开发员的软件开发工具包。1.5:{自动拆箱和装箱、foreach循环、可变参数}​1.8:{1、Lamdba表达式2、函数式接口3、方法引用和构造引用4、StreamAPI}​java的运行机制,编写定义为.java格式的源代码。​通过javac命令格式调用编译器(JDK)对源代码进行编......
  • java http大文件断点续传上传功能
    ​ 我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用。这次项目的需求:支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,ie8,ie9,Chrome,Firefox,360安全浏览器,并且刷新浏览器后仍然能够续传,重启浏览器(关闭......
  • 解决Java 线程池 共享变量的具体操作步骤
    实现Java线程池共享变量的步骤为了实现Java线程池共享变量,我们需要以下步骤:步骤描述步骤一创建一个线程池步骤二创建一个共享变量步骤三在需要共享变量的地方,使用线程池提交任务步骤四在任务中使用共享变量进行操作下面我将详细介绍每一步的操作和所需......
  • 解决Java 线程安全的DateFormat的具体操作步骤
    Java线程安全的DateFormat在多线程的环境下使用Java的SimpleDateFormat类进行日期格式化操作时,可能会遇到线程安全的问题。这篇文章将会介绍为什么SimpleDateFormat不是线程安全的,以及如何解决这个问题。为什么SimpleDateFormat不是线程安全的?SimpleDateFormat是Java中用于格......
  • 解决Java 显示静态图片的具体操作步骤
    Java显示静态图片在Java中,我们可以使用多种方法来显示静态图片,无论是从本地文件系统加载,还是从远程服务器获取。本文将介绍几种常用的方法,并提供相应的代码示例。使用Swing显示图片Swing是Java的一个图形用户界面(GUI)工具包,提供了一系列的组件和工具来创建丰富的用户界面。其中,J......
  • 解决Java 随机LocalTime的具体操作步骤
    如何实现Java随机LocalTime简介在Java中,我们可以使用java.time.LocalTime类来表示一个不带时区的时间,它包含小时、分钟、秒以及纳秒。本文将介绍如何在Java中生成随机的LocalTime。流程下面是实现Java随机LocalTime的步骤:步骤描述1导入java.time包......
  • 如何实现Java 视频文件去水印的具体操作步骤
    Java视频文件去水印在现今的数字媒体时代,视频文件无疑是最为常见的媒体之一。然而,我们有时会遇到一些带有水印的视频文件,这些水印可能是广告、商标或其他标记,影响了视频的观看体验。本文将介绍如何使用Java语言去除视频文件中的水印,并提供相应的代码示例。第一步:了解视频文件格......