前提工作
1、仔细阅读腾讯云接口的详细介绍腾讯云接口网址https://cloud.tencent.com/document/product/1093/35691
2、接入步骤
生成自己的AppId、SecretId和SecretKey
3、创建一个Java项目在pom.xml配置文件中添加依赖
<!-- 注:这里只是示例版本号,请获取并替换为 最新的版本号 -->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.62</version>
</dependency>
4、添加完依赖在application.properties中配置SecretId和SecretKey
spring.SecretId=改成自己的SecretId
spring.SecretKey=改成自己的SecretKey
5、创建一个接口(VoiceService)
//带返回值的,可以返回翻译的结果
String Sentence();
6、创捷一个继承接口的具体方法类(VoiceServiceImpl)
@Service
public class VoiceServiceImpl implements VoiceService {
//取出application.properties配置中配置的secretId和secretKey的值
//并把值赋给对应的变量
@Value("${spring.secretId}")
private String secretId;
@Value("${spring.secretKey}")
private String secretKey;
@Override
public String Sentence() {
try{
Credential cred = new Credential(secretId, secretKey);
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("asr.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
clientProfile.setSignMethod("TC3-HMAC-SHA256");
AsrClient client = new AsrClient(cred, "ap-shanghai", clientProfile);
String params = "{\"ProjectId\":0,\"SubServiceType\":2,\"EngSerViceType\":\"16k_zh\",\"SourceType\":1,\"Url\":\"\",\"VoiceFormat\":\"wav\",\"UsrAudioKey\":\"session-123\"}";
SentenceRecognitionRequest req = SentenceRecognitionRequest.fromJsonString(params, SentenceRecognitionRequest.class);
//这里直接给出一个音频文件的本地路径
File file = new File("C:/Users/zhao/Desktop/ws.wav");
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
req.setDataLen(file.length());
inputFile.read(buffer);
inputFile.close();
String encodeData = Base64.getEncoder().encodeToString(buffer);
req.setData(encodeData);
SentenceRecognitionResponse resp = client.SentenceRecognition(req);
String result = resp.getResult();
return result;
} catch (TencentCloudSDKException | IOException e) {
System.out.println(e.toString());
}
return null;
}
}
7、创建controller层(VoiceController)
@Controller
public class VoiceController {
@Autowired
VoiceService voiceService;
@RequestMapping("voice")
@ResponseBody
public void voice(){
String result = voiceService.Sentence();
//在控制台打印翻译结果
System.out.println(result);
}
}
翻译结果将在控制台打印出来
总结:这只是腾讯云语音识别其中的一项功能:一句话识别。其它的二个功能,录音文件识别和实时语音识别具体的操作流程和上述代码及步骤相差不大。如果需要前端文件上传到数据库并根据返回的那个url来翻译可以参考我的另一篇关于文件上传的文章,把这两篇文章合二为一即可。 文件上传的文章https://blog.csdn.net/javaasd/article/details/105079879