一:前期准备
先登录到百度云进行登录:百度智能云-云智一体深入产业
二:代码实现
实现类
package com.example.demo.voice;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Base64;
import java.net.URLEncoder;
/**
* 百度云
* @return
* @throws IOException
*/
@Service
public class PublicclassAuthService {
public static final String API_KEY = "这里的参数去刚刚那里找";
public static final String SECRET_KEY = "这里的参数去刚刚那里找";
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
public static String audioRecognition(MultipartFile aa) throws IOException {
MediaType mediaType = MediaType.parse("application/json");
// speech 可以通过 getFileContentAsBase64("C:\fakepath\111.m4a") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
RequestBody body = RequestBody.create(mediaType, "{\"format\":\"m4a\",\"rate\":16000,\"channel\":1,\"cuid\":\"oKcuRmfbpbJt9KeMrO0mgtznH3wKS4Yu\",\"dev_pid\":80001,\"speech\":\""+PublicclassAuthService.getFileContentAsBase64(aa,false)+"\","+" \"len\":446990,\"token\":\"" + getAccessToken() + "\"}");
Request request = new Request.Builder()
.url("https://vop.baidu.com/pro_api")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
return response.body().string();
}
public static byte[] fileToBytes(MultipartFile file){
try {
return file.getBytes();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取文件base64编码
*
* @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
* @return base64编码信息,不带文件头
* @throws IOException IO异常
*/
static String getFileContentAsBase64(MultipartFile aa, boolean urlEncode) throws IOException {
byte[] b = fileToBytes(aa);
String base64 = Base64.getEncoder().encodeToString(b);
if (urlEncode) {
base64 = URLEncoder.encode(base64, "utf-8");
}
return base64;
}
/**
* 从用户的AK,SK生成鉴权签名(Access Token)
*
* @return 鉴权签名(Access Token)
* @throws IOException IO异常
*/
static String getAccessToken() throws IOException {
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
+ "&client_secret=" + SECRET_KEY);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/oauth/2.0/token")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
return new JSONObject(response.body().string()).getString("access_token");
}
}
控制器
@PostMapping("/audio")
public String audio(@RequestParam("file") MultipartFile file) throws IOException {
return PublicclassAuthService.audioRecognition(file);
}
接口测试