0

0

Spring Boot与百度AI语音识别API集成实践

WBOY

WBOY

发布时间:2024-05-31 15:13:29

|

584人浏览过

|

来源于51CTO.COM

转载

☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

spring boot与百度ai语音识别api集成实践

本专题系统讲解了如何利用Spring Boot集成音频识别技术,涵盖了从基础配置到复杂应用的方方面面。通过本文,读者可以了解到在智能语音填单、智能语音交互、智能语音检索等场景中,音频识别技术如何有效提升人机交互效率。无论是本地存储检索,还是云服务的集成,丰富的应用实例为开发者提供了全面的解决方案。继续深入研究和实践这些技术,将有助于推动智能应用的广泛普及和发展,提升各类业务的智能化水平。


Spring Boot与百度AI语音识别API集成实践

百度AI语音识别API是目前国内领先的语音识别服务之一,具备以下几个显著特点:

  1. 高准确率:依托百度大规模的语音库和深度学习技术,能够提供高准确率的语音识别结果。
  2. 多场景应用:支持远场、近场、多语种等多种场景的语音识别应用,覆盖电话客服、语音助手、智能音箱等多种应用场景。
  3. 灵活接入:提供HTTP接口,方便开发者在各种语言和框架中集成。
  4. 实时性:支持实时语音识别,对于需要实时反馈的应用场景非常适用。

配置并对接百度AI语音识别API

要使用百度AI语音识别API,首先需要在百度AI开放平台上注册账号并创建应用,获取API Key和Secret Key。

获取API Key和Secret Key:

  • 登录百度AI开放平台,创建一个语音识别应用,记录下分配的API Key和Secret Key。

Spring Boot项目配置:

  • 在项目的application.properties文件中添加以下配置:
baidu.ai.appId=your_app_id baidu.ai.apiKey=your_api_key baidu.ai.secretKey=your_secret_key

配置百度AI客户端:

需要引入百度AI的SDK,创建一个配置类来初始化客户端。

引入依赖:
pom.xml文件中添加百度语音识别SDK依赖。

 com.baidu.aip java-sdk 4.15.1 

创建配置类:

import com.baidu.aip.speech.AipSpeech; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class BaiduAIConfig { @Value("${baidu.ai.appId}") private String appId; @Value("${baidu.ai.apiKey}") private String apiKey; @Value("${baidu.ai.secretKey}") private String secretKey; @Bean public AipSpeech aipSpeech() { AipSpeech client = new AipSpeech(appId, apiKey, secretKey); // 可选:设置连接超时参数 client.setConnectionTimeoutInMillis(2000); client.setSocketTimeoutInMillis(60000); return client; } }

创建语音识别和转换功能的REST API

接下来,我们将创建一个REST API,用于接收语音并通过百度AI语音识别API进行转换。

创建Spring Boot主类:

Pi智能演示文档
Pi智能演示文档

领先的AI PPT生成工具

下载
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpeechRecognitionApplication { public static void main(String[] args) { SpringApplication.run(SpeechRecognitionApplication.class, args); } }

实现语音识别的REST API:

import com.baidu.aip.speech.AipSpeech; import com.baidu.aip.speech.AipSpeechResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import org.json.JSONObject; @RestController @RequestMapping("/api/speech") public class SpeechRecognitionController { @Autowired private AipSpeech aipSpeech; @PostMapping(value = "/recognize", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity recognizeSpeech(@RequestParam("audio") MultipartFile audioFile) throws IOException { // 将音频文件转为字节数组 byte[] audioData = audioFile.getBytes();  // 执行语音识别 JSONObject response = aipSpeech.asr(audioData, "pcm", 16000, null);  // 检查返回结果中的错误码 if (response.getInt("err_no") != 0) { return ResponseEntity.status(500).body(response.toString()); } // 返回识别结果 return ResponseEntity.ok(response.toString(4)); } }

注意:

  • audioFile.getBytes()方法将上传的音频文件转换为字节数组。
  • aipSpeech.asr方法接受音频数据、音频格式(如pcm)、采样率(如16000)以及其他可选参数。
  • response对象中包含了识别结果,如果err_no不为0,则表示识别出错。

测试 REST API:

可以使用工具(如Postman)或者编写测试类来测试上述API。

import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest class SpeechRecognitionApplicationTests { @Autowired private MockMvc mockMvc; @Test void testRecognizeSpeech() throws Exception { MockMultipartFile file = new MockMultipartFile( "audio", "test.pcm", "audio/wav", new byte[]{/* test audio data */}); mockMvc.perform(MockMvcRequestBuilders.multipart("/api/speech/recognize") .file(file)) .andExpect(status().isOk()); } }

项目中的优化与调试方法

  1. 优化连接和请求
  • 适当设置连接超时和读取超时,以提高请求的响应速度和稳定性。
  1. 错误处理
  • 增加错误处理逻辑,例如网络错误、API调用错误,并提供详细的错误信息。

@PostMapping(value = "/recognize", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity recognizeSpeech(@RequestParam("audio") MultipartFile audioFile) { try { byte[] audioData = audioFile.getBytes(); JSONObject response = aipSpeech.asr(audioData, "pcm", 16000, null); if (response.getInt("err_no") != 0) { return ResponseEntity.status(500).body("Error: " + response.optString("err_msg")); } return ResponseEntity.ok(response.toString(4)); } catch (IOException e) { return ResponseEntity.status(500).body("File read error: " + e.getMessage()); } catch (Exception e) { return ResponseEntity.status(500).body("Unexpected error: " + e.getMessage()); } }


日志记录

使用日志记录API调用过程中的关键事件和错误信息,方便调试和定位问题。

import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import org.json.JSONObject;import com.baidu.aip.speech.AipSpeech;import java.io.IOException;@RestController@RequestMapping("/api/speech")public class SpeechRecognitionController {private static final Logger logger = LoggerFactory.getLogger(SpeechRecognitionController.class);@Autowiredprivate AipSpeech aipSpeech;@PostMapping(value = "/recognize", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)public ResponseEntity recognizeSpeech(@RequestParam("audio") MultipartFile audioFile) {try {byte[] audioData = audioFile.getBytes();logger.info("接收到的音频文件大小: {}", audioData.length);JSONObject response = aipSpeech.asr(audioData, "pcm", 16000, null);if (response.getInt("err_no") != 0) {logger.error("语音识别错误: {}", response.optString("err_msg"));return ResponseEntity.status(500).body("错误: " + response.optString("err_msg"));}logger.info("识别结果: {}", response.toString(4));return ResponseEntity.ok(response.toString(4));} catch (IOException e) {logger.error("文件读取错误", e);return ResponseEntity.status(500).body("文件读取错误: " + e.getMessage());} catch (Exception e) {logger.error("意外错误", e);return ResponseEntity.status(500).body("意外错误: " + e.getMessage());}}}

总结

通过这篇文章,我们详细介绍了如何在Spring Boot 3.x项目中集成百度AI语音识别API。我们探讨了API的特点、配置方法、创建REST API以实现语音识别功能、以及优化和调试的最佳实践。希望这篇文章能够帮助你在实际项目中实现高效的语音识别功能。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

98

2025.08.06

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

135

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

384

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

64

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

11

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

101

2025.12.24

软件测试常用工具
软件测试常用工具

软件测试常用工具有Selenium、JUnit、Appium、JMeter、LoadRunner、Postman、TestNG、LoadUI、SoapUI、Cucumber和Robot Framework等等。测试人员可以根据具体的测试需求和技术栈选择适合的工具,提高测试效率和准确性 。

428

2023.10.13

pdf怎么转换成xml格式
pdf怎么转换成xml格式

将 pdf 转换为 xml 的方法:1. 使用在线转换器;2. 使用桌面软件(如 adobe acrobat、itext);3. 使用命令行工具(如 pdftoxml)。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

1852

2024.04.01

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号