以byte[]数组的形式返回给前端听录音
controll控制层
@RequestMapping("/callSound")
public byte[] callSound(HttpServletResponse binResponse,
@RequestParam("callId") String callId,@RequestParam(value = "phone",required = false) String phone) {
binResponse.setHeader("Accept-Ranges", "bytes");
return callRegister.downloadCallSound(binResponse, callId,phone);
service业务层
public byte[] downloadCallSound(HttpServletResponse binResponse, String callId,String phone) {
//链接
HttpsURLConnection urlconn = null;
//接收流
BufferedInputStream bis = null;
//接收文件
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = null;
try {
FileInputStream fileInputStream = null;
try {
//保存在服务器里面的绝对路径
File pathLocal = new File("/opt/luyin/records");
//这里的id可以是音乐的关键id
File localFile = new File(pathLocal, "/" + id + ".wav");
logger.info("听录音路径:{}", localFile);
fileInputStream = new FileInputStream(localFile);
// 开始接收返回的数据
bis = new BufferedInputStream(fileInputStream);
} catch (Exception e) {
//根据链接听录音 类似于这样的 https://mp3.jiuku.9ku.com/hot/2005/08-11/68772.mp3
String str = "https://mp3.jiuku.9ku.com/hot/2005/08-11/68772.mp3";
urlconn = this.getConnection(str);
// 开始接收返回的数据
bis = new BufferedInputStream(urlconn.getInputStream());
}
//准备写入数据
byte[] buffer = new byte[1024 * 8];
int read;
while ((read = bis.read(buffer)) > -1) {
bos.write(buffer, 0, read);
}
//获取流数组
bytes = bos.toByteArray();
if (urlconn != null) {
urlconn.disconnect();
}
} catch (Exception e) {
logger.error("录音下载异常",e);
} finally {
//资源关闭处理
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlconn != null) {
urlconn.disconnect();
}
}
return bytes;
}
/**
* 获取链接
* @param path
* @return
*/
private HttpsURLConnection getConnection(String path) {
HttpsURLConnection urlconn = null;
try {
//自定义认证
TrustManager[] trustAllCerts = {new TrustAllManager()};
//跳过host认证
HostnameVerifier allHostsValid = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// 创建认证管理
SSLContext sc = SSLContext.getInstance("SSL");
SSLSessionContext ssls = sc.getServerSessionContext();
ssls.setSessionTimeout(0);
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
//会话创建
URL url = new URL(path);
urlconn = (HttpsURLConnection) url.openConnection();
urlconn.setDoInput(true);// 设置输入流采用字节流模式
urlconn.setDoOutput(true);
urlconn.setRequestMethod("GET");
// post请求不能使用缓存
urlconn.setUseCaches(false);
urlconn.setRequestProperty("Content-Type", "application/json");
urlconn.setConnectTimeout(5000);
urlconn.setReadTimeout(8000);
//链接服务器并发送消息
urlconn.connect();
} catch (Exception e) {
logger.error("链接异常",e);
}
return urlconn;
}