集成 EdgeTTS 到 Spring Boot 项目

EdgeTTS 是微软提供的免费文本转语音服务,可以通过 HTTP 请求调用。以下步骤展示如何在 Spring Boot 项目中集成 EdgeTTS 实现 TTS 功能。

添加依赖

pom.xml 中添加必要的依赖,包括 Spring Boot Web 和 Apache HttpClient:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

创建配置类

创建一个配置类来初始化 RestTemplateHttpClient

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpClientConfig {
    @Bean
    public CloseableHttpClient httpClient() {
        return HttpClients.createDefault();
    }
}

实现 EdgeTTS 服务

创建一个服务类来处理文本转语音请求:

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class EdgeTTSService {

    @Autowired
    private CloseableHttpClient httpClient;

    public byte[] convertTextToSpeech(String text, String voiceName) throws IOException {
        HttpPost httpPost = new HttpPost("https://edgeservices.bing.com/tts");
        httpPost.setHeader("Content-Type", "application/ssml+xml");
        httpPost.setHeader("X-Microsoft-OutputFormat", "audio-16khz-128kbitrate-mono-mp3");

        String ssml = "<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>" +
                "<voice name='" + voiceName + "'>" + text + "</voice></speak>";

        httpPost.setEntity(new StringEntity(ssml));

        return httpClient.execute(httpPost, response -> {
            return EntityUtils.toByteArray(response.getEntity());
        });
    }
}

创建控制器

添加一个控制器来暴露 API 接口:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/tts")
public class TTSController {

    @Autowired
    private EdgeTTSService edgeTTSService;

    @PostMapping
    public ResponseEntity<byte[]> convertToSpeech(@RequestBody String text, @RequestParam(defaultValue = "en-US-GuyNeural") String voice) throws IOException {
        byte[] audio = edgeTTSService.convertTextToSpeech(text, voice);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
                .body(audio);
    }
}

测试 API

启动 Spring Boot 应用后,可以使用以下 curl 命令测试 API:

curl -X POST "http://localhost:8080/api/tts" \
-H "Content-Type: text/plain" \
-d "Hello, this is a test message" \
--output test.mp3

可选语音列表

EdgeTTS 支持多种语音,部分常用语音名称如下:

  • en-US-GuyNeural(美式英语男声)
  • en-US-JennyNeural(美式英语女声)
  • zh-CN-YunxiNeural(中文普通话男声)
  • zh-CN-XiaoxiaoNeural(中文普通话女声)

完整语音列表可参考微软官方文档。

错误处理

建议添加异常处理逻辑以增强服务稳定性:

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(IOException.class)
    public ResponseEntity<String> handleIOException(IOException e) {
        return ResponseEntity.status(500).body("TTS service error: " + e.getMessage());
    }
}

性能优化

对于高频使用场景,可以考虑以下优化措施:

  • 实现音频缓存机制,避免重复转换相同文本
  • 使用连接池管理 HTTP 连接
  • 增加异步处理支持

以上步骤完整实现了 Spring Boot 与 EdgeTTS 的集成,开发者可以根据实际需求进一步扩展功能。

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐