springboot调用百度文字转语音
时间: 2025-03-07 21:01:19 浏览: 20
实现 Spring Boot 调用百度文字转语音 API
为了在 Spring Boot 项目中集成并使用百度的文字转语音 (TTS) API,需遵循特定的设置流程。此过程涉及创建百度智能云账号、获取访问密钥以及编写必要的 Java 代码来发起 HTTP 请求。
创建百度智能云账户和获取 API 密钥
首先,在百度智能云平台上注册一个开发者账号,并申请 TTS 服务权限。完成身份验证后,进入控制台找到对应的服务页面,记录下分配给用户的 API Key
和 Secret Key
这两个重要参数用于后续的身份认证[^1]。
添加依赖项到 pom.xml 文件
确保项目的 Maven 构建文件包含了处理 JSON 数据的能力以及其他可能需要用到的支持库:
<dependencies>
<!-- 百度 AIP SDK -->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>5.0.2</version>
</dependency>
<!-- Http Client 库 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1</version>
</dependency>
<!-- Jackson Core Library For Json Processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- Spring Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
编写控制器和服务层逻辑
定义 RESTful 接口接收客户端发送过来待合成的声音文本字符串,并通过调用百度提供的接口返回 MP3 或 WAV 格式的音频流数据作为响应体的一部分。
@RestController
@RequestMapping("/api/tts")
public class TextToSpeechController {
@Autowired
private BaiduAipService baiduAipService;
@PostMapping(value = "/synthesize", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<Resource> synthesize(@RequestParam String text, HttpServletResponse response){
try {
byte[] audioBytes = baiduAipService.synthesize(text);
InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(audioBytes));
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=synthesized_audio.mp3");
return ResponseEntity.ok()
.headers(headers)
.contentLength(audioBytes.length)
.body(resource);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
}
接着是负责实际业务处理的服务组件部分:
@Service
@Slf4j
public class BaiduAipServiceImpl implements BaiduAipService {
private final AipSpeech client;
public BaiduAipServiceImpl(){
this.client = new AipSpeech("your_api_key","your_secret_key","");
// 可选:设置连接超时时间和其他选项...
client.setConnectionTimeoutInMillis(2000L);
client.setSocketTimeoutInMillis(60000L);
}
@Override
public byte[] synthesize(String text)throws Exception{
JSONObject res = client.text2audio(text,"zh",1,null);
int errorCode = res.getInt("err_no");
if(errorCode != 0){
log.error("Error occurred while synthesizing speech: {}",res.getString("err_msg"));
throw new RuntimeException(res.getString("err_msg"));
}
return Base64.getDecoder().decode((String)res.getJSONObject("result").get("data"));
}
}
上述代码片段展示了如何利用百度官方提供的 Java SDK 来简化与云端服务器之间的交互操作。注意替换掉 "your_api_key"
和 "your_secret_key"
占位符为之前从百度获得的真实凭证信息。
配置 application.properties 文件
最后一步是在应用程序属性配置文件中指定一些默认行为或者环境变量映射关系以便于灵活管理不同部署场景下的差异之处:
server.port=8090
baidu.api.key=${BAIDU_API_KEY} # 使用环境变量覆盖硬编码值
baidu.secret.key=${BAIDU_SECRET_KEY}
logging.level.com.example=DEBUG # 设置日志级别方便调试期间查看输出消息
这样就完成了整个功能模块的设计与实现工作。当一切准备妥当时启动应用即可测试效果了!
阅读全文
相关推荐
















