主要实现方式:
1.将amr文件转化成base64字符串
2.用js转换成音频播放
js文件下载链接: https://pan.baidu.com/s/1kWsLOc3 密码: 2ca5
链接: https://pan.baidu.com/s/1smk2fdN 密码: qcbw
https://blog.csdn.net/hanglove_lucky/article/details/79106314
服务端:将网络文件转为 base64格式
public void fileToBase64(){
String urlStr = getPara("url");
URL url = null;
try {
url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
String text = Base64.encode(bos.toByteArray());
bos.close();
System.out.println(text);
renderText(text);
return;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
renderText("");
}
前端页面:
<!DOCTYPE HTML>
<html>
<head>
<script src="audio.min.js"></script>
</head>
<script src="voice-2.0.js"></script>
<script>
audiojs.events.ready(function() {
var as = audiojs.createAll();
});
</script>
<body>
<input type="button" value="play" id="playId"/>
<input type="button" value="stop" id="stopId"/>
</body>
<script type="text/javascript">
RongIMLib.RongIMVoice.init();
document.getElementById("playId").onclick = function(){
$.ajax({ url: "fileToBase64", data: { url:url }, cache: false, dataType: "text", success: function(_data) { if(_data != ""){ RongIMLib.RongIMVoice.play(_data); } }, error:function (xhr){ } });
};
document.getElementById("stopId").onclick = function(){
RongIMLib.RongIMVoice.stop();
};
</script>
</html>