找回密码
 立即注册
首页 业界区 业界 Spring Boot 集成免费的 EdgeTTS 实现文本转语音 ...

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

端木茵茵 昨天 16:30
在需要文本转语音(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模块:
  1. <dependencies>
  2.     <dependency>
  3.         <groupId>org.springframework.boot</groupId>
  4.         spring-boot-starter-web</artifactId>
  5.     </dependency>
  6. </dependencies>
复制代码
2. 注册 UnifiedTTS,获取 API Key


  • 前往 UnifiedTTS 官网注册账号(直接GitHub登录即可)
  • 从左侧菜单进入“API密钥”页面,创建 API Key;
1.png


  • 存好API Key,后续需要使用
3. 集成 UnifiedTTS API

下面根据API 文档:https://unifiedtts.com/zh/api-docs/tts-sync  实现一个可运行的参考实现,包括配置文件、请求模型、服务类与控制器。
3.1 配置文件(application.properties)
  1. unified-tts.host=https://unifiedtts.com
  2. unified-tts.api-key=your-api-key-here
复制代码
这里unifiedtts.api-key参数记得替换成之前创建的ApiKey。
3.2 配置加载类
  1. @Data
  2. @ConfigurationProperties(prefix = "unified-tts")
  3. public class UnifiedTtsProperties {
  4.     private String host;
  5.     private String apiKey;
  6. }
复制代码
3.3 请求封装和响应封装
  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. public class UnifiedTtsRequest {
  5.    
  6.     private String model;
  7.     private String voice;
  8.     private String text;
  9.     private Double speed;
  10.     private Double pitch;
  11.     private Double volume;
  12.     private String format;
  13. }
  14. @Data
  15. @AllArgsConstructor
  16. @NoArgsConstructor
  17. public class UnifiedTtsResponse {
  18.     private boolean success;
  19.     private String message;
  20.     private long timestamp;
  21.     private UnifiedTtsResponseData data;
  22.     @Data
  23.     @AllArgsConstructor
  24.     @NoArgsConstructor
  25.     public static class UnifiedTtsResponseData {
  26.         @JsonProperty("request_id")
  27.         private String requestId;
  28.         @JsonProperty("audio_url")
  29.         private String audioUrl;
  30.         @JsonProperty("file_size")
  31.         private long fileSize;
  32.     }
  33. }
复制代码
UnifiedTTS 抽象了不同模型的请求,这样用户可以用同一套请求参数标准来实现对不同TTS模型的调用,这个非常方便。所以,为了简化TTS的客户端调用,非常推荐使用 UnifiedTTS。
3.3 服务实现(调用 UnifiedTTS)

使用 Spring Boot自带的RestClient HTTP客户端来实现UnifiedTTS的功能实现类,提供两个实现:

  • 接收音频字节并返回。
  1. @Service
  2. public class UnifiedTtsService {
  3.     private final RestClient restClient;
  4.     private final UnifiedTtsProperties properties;
  5.     public UnifiedTtsService(RestClient restClient, UnifiedTtsProperties properties) {
  6.         this.restClient = restClient;
  7.         this.properties = properties;
  8.     }
  9.     /**
  10.      * 调用 UnifiedTTS 同步 TTS 接口,返回音频字节数据。
  11.      *
  12.      * <p>请求头:
  13.      * <ul>
  14.      *   <li>Content-Type: application/json</li>
  15.      *   <li>X-API-Key: 来自配置的 API Key</li>
  16.      *   <li>Accept: 接受二进制流或常见 mp3/mpeg 音频类型</li>
  17.      * </ul>
  18.      *
  19.      * @param request 模型、音色、文本、速度/音调/音量、输出格式等参数
  20.      * @return 音频二进制字节(例如 mp3)
  21.      * @throws IllegalStateException 当服务端返回非 2xx 或无内容时抛出
  22.      */
  23.     public byte[] synthesize(UnifiedTtsRequest request) {
  24.         ResponseEntity<byte[]> response = restClient
  25.                 .post()
  26.                 .uri("/api/v1/common/tts-sync")
  27.                 .contentType(MediaType.APPLICATION_JSON)
  28.                 .accept(MediaType.APPLICATION_OCTET_STREAM, MediaType.valueOf("audio/mpeg"), MediaType.valueOf("audio/mp3"))
  29.                 .header("X-API-Key", properties.getApiKey())
  30.                 .body(request)
  31.                 .retrieve()
  32.                 .toEntity(byte[].class);
  33.         if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
  34.             return response.getBody();
  35.         }
  36.         throw new IllegalStateException("UnifiedTTS synthesize failed: " + response.getStatusCode());
  37.     }
  38.     /**
  39.      * 调用合成并将音频写入指定文件。
  40.      *
  41.      * <p>若输出路径的父目录不存在,会自动创建;失败时抛出运行时异常。
  42.      *
  43.      * @param request TTS 请求参数
  44.      * @param outputPath 目标文件路径(例如 output.mp3)
  45.      * @return 实际写入的文件路径
  46.      */
  47.     public Path synthesizeToFile(UnifiedTtsRequest request, Path outputPath) {
  48.         byte[] data = synthesize(request);
  49.         try {
  50.             if (outputPath.getParent() != null) {
  51.                 Files.createDirectories(outputPath.getParent());
  52.             }
  53.             Files.write(outputPath, data);
  54.             return outputPath;
  55.         } catch (IOException e) {
  56.             throw new RuntimeException("Failed to write TTS output to file: " + outputPath, e);
  57.         }
  58.     }
  59. }
复制代码
3.4 单元测试
  1. @SpringBootTest
  2. class UnifiedTtsServiceTest {
  3.     @Autowired
  4.     private UnifiedTtsService unifiedTtsService;
  5.     @Test
  6.     void testRealSynthesizeAndDownloadToFile() throws Exception {
  7.         UnifiedTtsRequest req = new UnifiedTtsRequest(
  8.             "edge-tts",
  9.             "en-US-JennyNeural",
  10.             "Hello, this is a test of text to speech synthesis.",
  11.             1.0,
  12.             1.0,
  13.             1.0,
  14.             "mp3"
  15.         );
  16.         // 调用真实接口,断言返回结构
  17.         UnifiedTtsResponse resp = unifiedTtsService.synthesize(req);
  18.         assertNotNull(resp);
  19.         assertTrue(resp.isSuccess(), "Response should be success");
  20.         assertNotNull(resp.getData(), "Response data should not be null");
  21.         assertNotNull(resp.getData().getAudioUrl(), "audio_url should be present");
  22.         // 在当前工程目录下生成测试结果目录并写入文件
  23.         Path projectDir = Paths.get(System.getProperty("user.dir"));
  24.         Path resultDir = projectDir.resolve("test-result");
  25.         Files.createDirectories(resultDir);
  26.         Path out = resultDir.resolve(System.currentTimeMillis() + ".mp3");
  27.         Path written = unifiedTtsService.synthesizeToFile(req, out);
  28.         System.out.println("UnifiedTTS test output: " + written.toAbsolutePath());
  29.         assertTrue(Files.exists(written), "Output file should exist");
  30.         assertTrue(Files.size(written) > 0, "Output file size should be > 0");
  31.     }
  32. }
复制代码
4. 运行与验证

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

5. 常用参数与音色选择

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

对于model和voice参数可以因为内容较多,可以前往API文档查看。
小结

本文展示了如何在 Spring Boot 中集成 UnifiedTTS 的 EdgeTTS 能力,实现文本转语音并输出为 mp3。UnifiedTTS 通过统一的 API 屏蔽了不同 TTS 模型的差异,使你无需维护多个 SDK,即可在成本与效果之间自由切换。根据业务需求,你可以进一步完善异常处理、缓存与并发控制,实现更可靠的生产级 TTS 服务。
本文样例工程:https://github.com/dyc87112/unified-tts-example

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册