如何使用Spring AI 实现文本转语音(TTS:Text-to-Speech )?

Spring AI文本转语音(TTS:Text-to-Speech)入门示例

目录

Spring AI文本转语音(TTS:Text-to-Speech)入门示例

1、Text-to-Speech API概述

2、Spring Boot集成Spring AI框架

3、创建SpeechController

4、启动Springboot工程并测试


本章节示例演示如何基于Spring Boot集成Spring AI开源框架,快速集成调用阿里云的百炼大模型AI服务,验证AI大模型“文本转语音”的功能。

欢迎关注我的公众号

1、Text-to-Speech API概述

在Spring AI框架中,Text-to-Speech API提供了一个基于OpenAI的TTS(文本转语音)模型的语音端点,使用户能够:

  • 朗读写好的博客文章。

  • 生成多种语言的语音音频。

  • 使用流媒体实现实时音频输出。

这一功能强大的API让用户可以轻松地将文字内容转化为语音内容,不仅支持多语言转换,还能满足实时语音输出的需求,极大地提升了内容的可访问性和用户的体验感。

2、Spring Boot集成Spring AI框架

如何基于Springboot集成Spring AI框架,并调用阿里云AI服务,请参考文章Spring AI Alibaba入门示例,这里不再重复说明。

3、创建SpeechController

本示例使用spring ai alibaba开源框架,SpeechSynthesisModel 类是Spring AI Alibaba框架中用于表示和管理文本转语音模型的核心组件之一。

DashScopeSpeechSynthesisOptions 类通常用于配置文本转语音(TTS)服务的选项,这个类允许开发者指定一系列参数(比如:语速、音调、音量等)来定制化语音合成的结果,从而满足不同的应用场景需求。

package com.wcy.ai.controller;import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;import jakarta.annotation.PreDestroy;import lombok.extern.slf4j.Slf4j;import org.apache.tomcat.util.http.fileupload.FileUtils;import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import reactor.core.publisher.Flux;import java.io.*;import java.nio.ByteBuffer;import java.util.concurrent.CountDownLatch;/** * @desc 文本转语音(Text-To-Speech) * @date: 2025/3/11 * @version: 1.0 */@Slf4j@RestController@RequestMapping("/ai")public class SpeechController implements ApplicationRunner {    private final SpeechSynthesisModel speechSynthesisModel;    private static final String TEXT = "床前明月光, 疑是地上霜。 举头望明月, 低头思故乡。";    private static final String FILE_PATH = "src/main/resources/tts";    public SpeechController(SpeechSynthesisModel speechSynthesisModel) {        this.speechSynthesisModel = speechSynthesisModel;    }
    @GetMapping("/tts")    public void tts() throws IOException {        // 使用构建器模式创建 DashScopeSpeechSynthesisOptions 实例并设置参数        DashScopeSpeechSynthesisOptions options = DashScopeSpeechSynthesisOptions.builder()                .withSpeed(1.0)        // 设置语速                .withPitch(0.9)         // 设置音调                .withVolume(60)         // 设置音量                .build();        SpeechSynthesisResponse response = speechSynthesisModel.call(new SpeechSynthesisPrompt(TEXT,options));        File file = new File(FILE_PATH + "/output.mp3");        try (FileOutputStream fos = new FileOutputStream(file)) {            ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();            fos.write(byteBuffer.array());        } catch (IOException e) {            log.error(e.getMessage(), e);            throw new IOException(e.getMessage());        }    }
    @GetMapping("/ttsStream")    public void ttsStream() {        Flux<SpeechSynthesisResponse> response = speechSynthesisModel.stream(new SpeechSynthesisPrompt(TEXT));        CountDownLatch latch = new CountDownLatch(1);        File file = new File(FILE_PATH + "/output-stream.mp3");        try (FileOutputStream fos = new FileOutputStream(file)) {            response.doFinally(signal -> latch.countDown())                    .subscribe(synthesisResponse -> {                ByteBuffer byteBuffer = synthesisResponse.getResult().getOutput().getAudio();                byte[] bytes = new byte[byteBuffer.remaining()];                byteBuffer.get(bytes);                try {                    fos.write(bytes);                }                catch (IOException e) {                    throw new RuntimeException(e);                }            });            latch.await();        } catch (IOException | InterruptedException e) {            log.error(e.getMessage(), e);            throw new RuntimeException(e);        }    }
    @Override    public void run(ApplicationArguments args) {        File file = new File(FILE_PATH);        if (!file.exists()) {            file.mkdirs();        }    }
    @PreDestroy    public void destroy() throws IOException {        FileUtils.deleteDirectory(new File(FILE_PATH));    }}

4、启动Springboot工程并测试

启动成功后把下面地址输入到浏览器里,验证AI大模型文本转语音功能:

http://localhost:8080/ai/tts

http://localhost:8080/ai/ttsStream

执行完成后,在工程目录下src/main/resources/tts看到生成的语音文件

output.mp3、output-steam.mp3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

棉花糖老丫

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

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

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

打赏作者

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

抵扣说明:

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

余额充值