一、调用微信录音接口前端
1、获取微信签名
使用ajax去后台获取微信签名
2、微信配置
wx.config({
// beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: data.appId, // 必填,企业微信的corpID
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.nonceStr, // 必填,生成签名的随机串
signature: data.signature,// 必填,签名,见附录1
jsApiList: ['startRecord','stopRecord','playVoice','onVoiceRecordEnd','uploadVoice'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function(){
//按下开始录音
$("#talk").on('touchstart',function(event){
event.preventDefault();
START = new Date().getTime();
recordTimer = setTimeout(function(){
wx.startRecord({
success: function(){
localStorage.rainAllowRecord = 'true';
$("#start").css("display","block");
},
cancel: function () {
$("#start").css("display","block");
$("#start").html("用户拒绝授权录音");
}
});
},300);
});
//松手停止录音
$("#talk").on('touchend',function(event){
event.preventDefault();
END = new Date().getTime();
if((END - START) < 300){
END = 0;
START = 0;
//小于300ms,不录音
clearTimeout(recordTimer);
}else{
wx.stopRecord({
success: function (res) {
$("#end").css("display","block");
localId = res.localId;
uploadVoice();
},
fail: function (res) {
$("#end").css("display","block");
$("#end").html("录音失败!");
alert("失败"+JSON.stringify(res));
}
});
}
uploadVoice();
});
//播放语音接口
$("#bf").click(function(){
wx.playVoice({
localId: localId // 需要播放的音频的本地ID,由stopRecord接口获得
});
})
//监听录音自动停止接口
wx.onVoiceRecordEnd({
// 录音时间超过一分钟没有停止的时候会执行 complete 回调
complete: function (res) {
var localId = res.localId;
}
});
//上传录音
function uploadVoice(){
//调用微信的上传录音接口把本地录音先上传到微信的服务器
//不过,微信只保留3天,而我们需要长期保存,我们需要把资源从微信服务器下载到自己的服务器
wx.uploadVoice({
localId: localId, // 需要上传的音频的本地ID,由stopRecord接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
//把录音在微信服务器上的id(res.serverId)发送到自己的服务器供下载。
// data: JSON.stringify(res),
$.ajax({
url: basePath + '/weixin/video_insertVoice.do?serverId='+res.serverId,
type: 'post',
dataType: "json",
success: function (data) {
alert('文件已经保存到服务器!');
},
error: function (xhr, errorType, error) {
console.log(error);
}
});
}
});
}
});
wx.error(function(res){
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});
页面效果如下:
二、微信api的缺陷是存储的录音文件不是mp3格式、而是amr文件格式
后端需将amr转换为MP3的格式并上传到服务器
//1.调用微信提供的接口serverId获取录音的InputStream字节流
public InputStream getInputStream(String mediaId) {
InputStream is = null;
HttpURLConnection http;
try {
String access_token=WxUtil.getAccessToken();
String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+serverId;
URL urlGet = new URL(url);
http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
// 获取文件转化为byte流
is = http.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return is;
}
//2.将获取到的字节流保存为amr文件
public String downloadMediaId( String mediaId,String savePath) {
String relfilePath = null;
InputStream inputStream = getInputStream(mediaId);
FileOutputStream fileOutputStream = null;
try {
//服务器资源保存路径
//临时路径
//String path=TemplateUtil.getTempPath();
//String savePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + DateUtil.getYear(new Date()) + "/wxmedia/audio/";
//savePath = savePath + "audio/";
String filename = String.valueOf(System.currentTimeMillis()) + ".amr";
relfilePath = savePath + filename;
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
byte[] data = new byte[1024];
int len = 0;
fileOutputStream = new FileOutputStream(savePath + filename);
while ((len = inputStream.read(data)) != -1) {
// 判断结果是否有错
if (new String(data).indexOf("errmsg") > -1) {
return null;
}
fileOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return relfilePath;
}
/**
* @author yfc
* @createTime 2019年6月27日 下午2:29:34
* @description 4、音频存入,将MP3文件上传至服务器
*/
public void insertVoice(){
logger.info("================================临时文件路径:"+TemplateUtil.getTempPath());
String sourcePath="d:/upload/a.mp3";
String savepath=request.getSession().getServletContext().getRealPath("/") + "upload/" + DateUtil.getYear(new Date()) + "/wxmedia/audio/";
logger.info("================================savepath:"+savepath);
logger.info("================================serverId"+serverId);
//目标路径
String targetPath=downloadMediaId(serverId,savepath);
logger.info("================================targetPath:"+targetPath);
//arm转MP3
changeToMp3(targetPath, sourcePath);
try {
File fileName=new File(sourcePath);
FileInputStream file;
file = new FileInputStream(fileName);
String path=FileStoreService.uploadFile("voice",System.currentTimeMillis()+".mp3" , file);
logger.info("================================path:"+path);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
String path1 = "D:/upload/1562649533821.amr";
String path2 = "D:/upload/a.mp3";
changeToMp3(path1, path2);
}
//3、将amr文件转换为mp3格式
public static void changeToMp3(String sourcePath, String targetPath) {
File source = new File(sourcePath);
File target = new File(targetPath);
AudioAttributes audio = new AudioAttributes();
Encoder encoder = new Encoder();
audio.setCodec("libmp3lame");
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
attrs.setAudioAttributes(audio);
try {
encoder.encode(source, target, attrs);
} catch (Exception e) {
e.printStackTrace();
}
}
三、依赖jar包
com.github.dadiyang
jave
1.0.3