java 实现文本转音频


一、前言

本文基于Windows自带的SAPI.SpVoice,通过java代码实现文本转语音的功能。

二、实现流程

2.1 下载jacob-1.18.zip

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

2.2 拷贝jacob-1.18-x64.dll

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

2.3 pom 添加依赖

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

2.4 代码实现

    ---
    # 一、前言
    本文基于Windows自带的SAPI.SpVoice,通过java代码实现文本转语音的功能。
    # 二、实现流程
    ## 2.1下载jacob-1.18.zip
    链接:https://pan.baidu.com/s/1-zYB9I4VF5cPuj3ok1WLyg
    提取码:7t1g
    ## 2.2拷贝jacob-1.18-x64.dll
    将 jacob-1.18-x64.dll拷贝到jdk的bin目录或windows/SysWOW64目录中
    ## 2.3pom 添加依赖

    ```yaml
com.hynnet jacob 1.18 ``` ## 2.4代码实现

package gisshare.demo.audio;

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:\\myWork/1111.txt");
        textToSpeechIO(text);
    }


    /**
     * 字符串文本转 wav格式 语音文件
     *
     * @param text 要读的文字字符串
     */
    public static void textToSpeechIO(String text) {
        String path = "D:\\myWork\\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));
    }
}

在这里插入图片描述

  • 11
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java可以通过使用第三方库来实现文本音频。以下是一个使用FreeTTS库的例子: 1. 首先需要下载FreeTTS库并将其添加到Java项目中。 2. 在Java代码中,可以使用以下代码实现文本音频: ``` import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.AudioInputStream; import com.sun.speech.freetts.Voice; import com.sun.speech.freetts.VoiceManager; public class TextToSpeech { public static void main(String[] args) throws Exception { // 设置要换的文本 String text = "你好,这是一个测试!"; // 初始化VoiceManager VoiceManager voiceManager = VoiceManager.getInstance(); // 选择要使用的音频引擎 Voice voice = voiceManager.getVoice("kevin16"); // 分配音频引擎资源 voice.allocate(); // 创建一个音频流,将换后的音频输出到其中 AudioInputStream audioStream = AudioSystem.getAudioInputStream(voice.synthesize(text)); // 保存音频文件 AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, new File("output.wav")); // 释放音频引擎资源 voice.deallocate(); } } ``` 在上面的代码中,我们首先设置要换的文本,然后选择使用的音频引擎。在本例中,我们使用了Kevin16音频引擎。然后,我们分配音频引擎资源并创建一个音频流,将换后的音频输出到其中。最后,我们将音频文件保存到本地,并释放音频引擎资源。 请注意,这个例子只是一个简单的演示,需要根据具体的需求进行修改和调整。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gis分享者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值