日期 版本 作者 说明
2022-11-22 V-1.0 孔留锋 文档新建。

语音转文字

简介

​ 移动端业务需求,实现语音转文字。允许移动端用户利用话筒,输入语音,并转成文字。

调研

​ 第三方公司提供的有相应的API,如阿里、百度、科大讯飞、华为等。因之前用过百度翻译相关产品,时间原因,首选百度提供的API。

百度语音识别

官方地址

语音识别极速版API

付费标准

免费测试资源 个人180天免费5W次。到期不能用。

采购价格:

image-20221122165138068

开发

准备工作

参考 :创建应用 获取 AppID、API Key及Secret Key 。

image-20221122142153141

Java 集成

1.pom文件引用

1
2
3
4
5
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.12</version>
</dependency>

2.VoiceConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
@Data
public class VoiceConfig {
@Value("${voice.app_id}")
private static final String APP_ID ="2857----";
@Value("${voice.app_key}")
private static final String API_KEY = "aMY0n6yWt4NAGPA4--------";
@Value("${voice.secret_key}")
private static final String SECRET_KEY = "kTDNw1pnOUgbK8FjuxrLet2O--------" ;

@Bean
public AipSpeech aipSpeech(){
AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
// 可选:设置网络连接参数
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
return client;
}
}

3.VoiceApi

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@RestController
@RequestMapping("/api/voice")
public class VoiceApi {
//注入ApiClent端
@Autowired
private AipSpeech aipSpeech;

/**
* @description 语音转文字
*
* @author kongliufeng
* @Date 2022-11-22
*/
@RequestMapping(value = "tran", method = RequestMethod.POST)
public Result tran(@RequestParam("file") MultipartFile file){
try{
byte[] bytes = file.getBytes();
JSONObject asrRes = aipSpeech.asr(bytes, "m4a", 16000, null);
if(asrRes.get("result")!=null){
return Result.OK(asrRes.get("result"));
}
}catch (Exception e){
e.printStackTrace();
}
return Result.error500();
}
}