Spring Boot实现文字转语音功能

文字转语音(TTS)在智能助手、有声读物等场景高频使用,今天用 Spring Boot 快速落地,全程聚焦代码与操作,新手也能跟着做。

一、准备工作:3 步搭好项目基础

1. 创建 Spring Boot 项目

打开 Spring Initializr,按以下配置选择:

  • 依赖:仅勾选 Spring Web (满足接口开发需求)

  • 打包方式:Jar

JDK 版本:11 或 17(兼容性更佳)

  • 点击 Generate 下载项目,解压后导入 IDEA。

2. 引入 TTS 依赖

pom.xml中添加 Google Text-to-Speech 依赖(轻量、无需密钥):

复制代码
dependency>
groupId>com.googlecode.javacvgroupId>
artifactId>javacv-platformartifactId>
version>1.5.8version>
dependency>
dependency>
groupId>com.google.cloudgroupId>
artifactId>google-cloud-texttospeechartifactId>
version>2.31.0version>
dependency>

刷新 Maven 下载依赖。

二、核心实战:写代码实现功能

二、核心实战:写代码实现功能

1. 配置 TTS 客户端

创建 TtsConfig.java,初始化 Google TTS 客户端(本地测试无需额外密钥,默认读取环境变量,若报错可参考 官方文档 配置密钥):

复制代码
import com.google.cloud.texttospeech.v1.TextToSpeechClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public classTtsConfig{
@Bean
public TextToSpeechClienttextToSpeechClient throws Exception {
// 初始化客户端
return TextToSpeechClient.create;
}
}

2. 写接口:接收文字 + 生成语音

创建 TtsController.java,提供 POST 接口,接收文字参数,生成 MP3 音频文件并返回文件路径:

复制代码
import com.google.cloud.texttospeech.v1.*;
import com.google.protobuf.ByteString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.FileOutputStream;
import java.io.OutputStream;
@RestController
public classTtsController{
@Autowired
private TextToSpeechClient ttsClient;// 接口:接收文字,生成语音文件
@PostMapping("/text-to-speech")
public StringtextToSpeech(@RequestParam String text) {
try {
// 1. 构建语音请求参数
SynthesisInput input = SynthesisInput.newBuilder.setText(text).build;// 2. 设置语音参数(中文、女声)
VoiceSelectionParams voice = VoiceSelectionParams.newBuilder.setLanguageCode("zh-CN") // 语言:中文
.setSsmlGender(SsmlVoiceGender.FEMALE) // 性别:女
.build;// 3. 设置音频格式(MP3)
AudioConfig audioConfig = AudioConfig.newBuilder.setAudioEncoding(AudioEncoding.MP3).build;// 4. 调用 TTS 接口生成音频
SynthesizeSpeechResponse response = ttsClient.synthesizeSpeech(input, voice, audioConfig);ByteString audioContent = response.getAudioContent;// 5. 保存音频到本地(路径可自定义)
String filePath ="D:/tts-output/"+ System.currentTimeMillis +".mp3";
try (OutputStream out = new FileOutputStream(filePath)) {
out.write(audioContent.toByteArray);}return"语音生成成功!路径:"+ filePath;
} catch (Exception e) {
return"生成失败:"+ e.getMessage;
}}}

三、测试运行:2 步验证功能

1. 启动项目

直接运行 Spring Boot 启动类(带 @SpringBootApplication注解的类),控制台显示

Started Application in XX seconds

表示启动成功。

2. 调用接口测试

用 Postman 或 Apifox 发送请求:

  • 方法:POST

URL:

http://localhost:8080/text-to-speech

参数: text=Spring Boot 文字转语音实战真简单!

  • 发送后,若返回「语音生成成功」,打开对应路径即可播放 MP3 音频。

四、关键注意点

若报「密钥不存在」错误:按 Google 官方指引 下载密钥文件,在 IDEA 中设置环境变量

GOOGLE_APPLICATION_CREDENTIALS=密钥文件路径

  1. 音频路径可修改:将代码中 D:/tts-output/改为自己的路径(如./tts/表示项目根目录)。

  2. 可调整语音参数:修改 VoiceSelectionParams中的languageCode(如en-US为英文)、SsmlVoiceGenderMALE为男声)。

相关推荐
应用市场9 小时前
构建自定义命令行工具 - 打造专属指令体
开发语言·windows·python
东方佑9 小时前
从字符串中提取重复子串的Python算法解析
windows·python·算法
Dfreedom.10 小时前
一文掌握Python四大核心数据结构:变量、结构体、类与枚举
开发语言·数据结构·python·变量·数据类型
一半烟火以谋生10 小时前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
虚行10 小时前
C#上位机工程师技能清单文档
开发语言·c#
小羊在睡觉10 小时前
golang定时器
开发语言·后端·golang
CoderCodingNo11 小时前
【GESP】C++四级真题 luogu-B4068 [GESP202412 四级] Recamán
开发语言·c++·算法
叶子丶苏11 小时前
第八节_PySide6基本窗口控件_按钮类控件(QAbstractButton)
python·pyqt
Larry_Yanan11 小时前
QML学习笔记(四十四)QML与C++交互:对QML对象设置objectName
开发语言·c++·笔记·qt·学习·ui·交互
百锦再11 小时前
对前后端分离与前后端不分离(通常指服务端渲染)的架构进行全方位的对比分析
java·开发语言·python·架构·eclipse·php·maven