3,143
社区成员
发帖
与我相关
我的任务
分享
wx.ready(function() {
var voice = {
localId: '',
serverId: ''
};
// 开始录音
$("#startRecord").click(function() {
wx.startRecord({
success: function() {
voice.localId = res.localId;
}
});
});
// 录音结束
$("#stopRecord").click(function() {
wx.stopRecord({
success: function(res) {
voice.localId = res.localId;
},
fail: function(res) {
alert(JSON.stringify(res));
}
});
});
// 4.8 上传语音
$("#uploadVoice").click(function() {
if(voice.localId == '') {
alert('请先使用 startRecord 接口录制一段声音');
return;
}
wx.uploadVoice({
localId: voice.localId,
success: function(res) {
voice.localId = res.localId;
alert('上传语音成功,serverId 为' + res.serverId);
voice.serverId = res.serverId;
alert("mediaId:"+voice.serverId);
$("span").text(voice.serverId);
$.ajax({
type: "get",
dataType: "json",
url: "/voiceLoad/saveVoice",
data: {
openId:openId,
mediaId: voice.serverId
},
success: function(data) {
if(data.isOk==1){
alert("本地服务器上传成功!")
voiceId=data.voiceId;
}
else{
alert("本地服务器上传失败!")
}
},
error:function(){
alert("error!")
}
});
},
fail: function(res) {
//alert(JSON.stringify(res));
alert("微信服务器上传失败!");
}
});
});
//触发播放音频的事件
$("#play").click(function(){
alert($("#myAudio").attr("src"))
if($("#myAudio").attr("src")!=undefined && $("#myAudio").attr("src")!=""){
alert("notundefined")
$("#myAudio")[0].load();
$("#myAudio").get(0).play();
}
})
// 4.9 下载语音
$("#downloadVoice").click(function() {
if(voice.serverId == '') {
alert('请先使用 uploadVoice 上传声音');
return;
}
$.ajax({
type: "get",
dataType: "json",
url: "/voiceLoad/getVoice",
data: {
voiceId:voiceId
},
success: function(data) {
if(data.isOk==1){
alert("voiceId:"+voiceId);
var ua=navigator.userAgent.toLowerCase();
if(/(Android)/i.test(navigator.userAgent)){
$("#myAudio").attr("src",data.filePath);
$("#myAudio").attr("autoplay","autoplay");
$("#myAudio")[0].load();
$("#myAudio").get(0).play();
}
else if(/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)){
alert("iphone")
//iphone手机尝试的方法1
/*document.addEventListener("WeixinJSBridgeReady", function () {
alert(data.filePath);
playMusic(data.filePath);
}, false);*/
//iphone手机尝试的方法2
document.getElementById("myAudio").setAttribute("src",data.filePath);
document.getElementById("myAudio").play();
$("#play").trriger("click");
}
}
else{
alert("本地服务器下载失败!")
}
}
});
});
function playMusic(src){
document.getElementById("myAudio").setAttribute("src",src);
document.getElementById("myAudio").play();
}
})