当前位置: 代码网 > it编程>编程语言>Java > SpringBoot集成免费的EdgeTTS实现文本转语音

SpringBoot集成免费的EdgeTTS实现文本转语音

2025年10月20日 Java 我要评论
引言在需要文本转语音(tts)的应用场景中(如语音助手、语音通知、内容播报等),java生态缺少类似python生态的edge tts 客户端库。不过没关系,现在可以通过 unifiedtts 提供的

引言

在需要文本转语音(tts)的应用场景中(如语音助手、语音通知、内容播报等),java生态缺少类似python生态的edge tts 客户端库。不过没关系,现在可以通过 unifiedtts 提供的 api 来调用免费的 edgetts 能力。同时,unifiedtts 还支持 azure tts、minimax tts、elevenlabs tts 等多种模型,通过对请求接口的抽象封装,用户可以方便在不同模型与音色之间灵活切换。

下面我们以调用免费的edgetts为目标,构建一个包含文本转语音功能的spring boot应用。

实战

1. 构建 spring boot 应用

通过 start.spring.io 或其他构建基础的spring boot工程,根据你构建应用的需要增加一些依赖,比如最后用接口提供服务的话,可以加入web模块:

<dependencies>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
</dependencies>

2. 注册 unifiedtts,获取 api key

  • 前往 unifiedtts 官网注册账号(直接github登录即可)
  • 从左侧菜单进入“api密钥”页面,创建 api key;

  • 存好api key,后续需要使用

3. 集成 unifiedtts api

下面根据api 文档:https://unifiedtts.com/zh/api-docs/tts-sync 实现一个可运行的参考实现,包括配置文件、请求模型、服务类与控制器。

3.1 配置文件(application.properties)

unified-tts.host=https://unifiedtts.com
unified-tts.api-key=your-api-key-here

这里unifiedtts.api-key参数记得替换成之前创建的apikey。

3.2 配置加载类

@data
@configurationproperties(prefix = "unified-tts")
public class unifiedttsproperties {

    private string host;
    private string apikey;

}

3.3 请求封装和响应封装

@data
@allargsconstructor
@noargsconstructor
public class unifiedttsrequest {
    
    private string model;
    private string voice;
    private string text;
    private double speed;
    private double pitch;
    private double volume;
    private string format;

}

@data
@allargsconstructor
@noargsconstructor
public class unifiedttsresponse {

    private boolean success;
    private string message;
    private long timestamp;
    private unifiedttsresponsedata data;

    @data
    @allargsconstructor
    @noargsconstructor
    public static class unifiedttsresponsedata {
        @jsonproperty("request_id")
        private string requestid;

        @jsonproperty("audio_url")
        private string audiourl;

        @jsonproperty("file_size")
        private long filesize;
    }
}

unifiedtts 抽象了不同模型的请求,这样用户可以用同一套请求参数标准来实现对不同tts模型的调用,这个非常方便。所以,为了简化tts的客户端调用,非常推荐使用 unifiedtts。

3.3 服务实现(调用 unifiedtts)

使用 spring boot自带的restclient http客户端来实现unifiedtts的功能实现类,提供两个实现:

  1. 接收音频字节并返回。
@service
public class unifiedttsservice {

    private final restclient restclient;
    private final unifiedttsproperties properties;

    public unifiedttsservice(restclient restclient, unifiedttsproperties properties) {
        this.restclient = restclient;
        this.properties = properties;
    }

    /**
     * 调用 unifiedtts 同步 tts 接口,返回音频字节数据。
     *
     * <p>请求头:
     * <ul>
     *   <li>content-type: application/json</li>
     *   <li>x-api-key: 来自配置的 api key</li>
     *   <li>accept: 接受二进制流或常见 mp3/mpeg 音频类型</li>
     * </ul>
     *
     * @param request 模型、音色、文本、速度/音调/音量、输出格式等参数
     * @return 音频二进制字节(例如 mp3)
     * @throws illegalstateexception 当服务端返回非 2xx 或无内容时抛出
     */
    public byte[] synthesize(unifiedttsrequest request) {
        responseentity<byte[]> response = restclient
                .post()
                .uri("/api/v1/common/tts-sync")
                .contenttype(mediatype.application_json)
                .accept(mediatype.application_octet_stream, mediatype.valueof("audio/mpeg"), mediatype.valueof("audio/mp3"))
                .header("x-api-key", properties.getapikey())
                .body(request)
                .retrieve()
                .toentity(byte[].class);

        if (response.getstatuscode().is2xxsuccessful() && response.getbody() != null) {
            return response.getbody();
        }
        throw new illegalstateexception("unifiedtts synthesize failed: " + response.getstatuscode());
    }

    /**
     * 调用合成并将音频写入指定文件。
     *
     * <p>若输出路径的父目录不存在,会自动创建;失败时抛出运行时异常。
     *
     * @param request tts 请求参数
     * @param outputpath 目标文件路径(例如 output.mp3)
     * @return 实际写入的文件路径
     */
    public path synthesizetofile(unifiedttsrequest request, path outputpath) {
        byte[] data = synthesize(request);
        try {
            if (outputpath.getparent() != null) {
                files.createdirectories(outputpath.getparent());
            }
            files.write(outputpath, data);
            return outputpath;
        } catch (ioexception e) {
            throw new runtimeexception("failed to write tts output to file: " + outputpath, e);
        }
    }
}

3.4 单元测试

@springboottest
class unifiedttsservicetest {

    @autowired
    private unifiedttsservice unifiedttsservice;

    @test
    void testrealsynthesizeanddownloadtofile() throws exception {
        unifiedttsrequest req = new unifiedttsrequest(
            "edge-tts",
            "en-us-jennyneural",
            "hello, this is a test of text to speech synthesis.",
            1.0,
            1.0,
            1.0,
            "mp3"
        );

        // 调用真实接口,断言返回结构
        unifiedttsresponse resp = unifiedttsservice.synthesize(req);
        assertnotnull(resp);
        asserttrue(resp.issuccess(), "response should be success");
        assertnotnull(resp.getdata(), "response data should not be null");
        assertnotnull(resp.getdata().getaudiourl(), "audio_url should be present");

        // 在当前工程目录下生成测试结果目录并写入文件
        path projectdir = paths.get(system.getproperty("user.dir"));
        path resultdir = projectdir.resolve("test-result");
        files.createdirectories(resultdir);
        path out = resultdir.resolve(system.currenttimemillis() + ".mp3");
        path written = unifiedttsservice.synthesizetofile(req, out);
        system.out.println("unifiedtts test output: " + written.toabsolutepath());
        asserttrue(files.exists(written), "output file should exist");
        asserttrue(files.size(written) > 0, "output file size should be > 0");
    }
}

4. 运行与验证

执行单元测试之后,可以在工程目录test-result下找到生成的音频文件:

5. 常用参数与音色选择

目前支持的常用参数如下图所示:

小结

本文展示了如何在 spring boot 中集成 unifiedtts 的 edgetts 能力,实现文本转语音并输出为 mp3。unifiedtts 通过统一的 api 屏蔽了不同 tts 模型的差异,使你无需维护多个 sdk,即可在成本与效果之间自由切换。根据业务需求,你可以进一步完善异常处理、缓存与并发控制,实现更可靠的生产级 tts 服务。

以上就是springboot集成免费的edgetts实现文本转语音的详细内容,更多关于springboot edgetts文本转语音的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com