微信语音上传 下载功能实例代码
假如现在有一个按钮
按住说话
下面就是调用微信jssdk的方法
varrecorder;
varbtnRecord=$('#record');
varstartTime=0;
varrecordTimer=300;
//发语音
$.ajax({
url:'url请求需要微信的一些东西下面success就是返回的东西',
type:'get',
data:{url:url},
success:function(data){
varjson=$.parseJSON(data);
//alert(json);
//假设已引入微信jssdk。【支持使用AMD/CMD标准模块加载方法加载】
wx.config({
debug:false,//开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId:json.appid,//必填,公众号的唯一标识
timestamp:json.timestamp,//必填,生成签名的时间戳
nonceStr:json.nonceStr,//必填,生成签名的随机串
signature:json.signature,//必填,签名,见附录1
jsApiList:[
"startRecord",
"stopRecord",
"onVoiceRecordEnd",
"playVoice",
"pauseVoice",
"stopVoice",
"onVoicePlayEnd",
"uploadVoice",
"downloadVoice",
]//必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function(){
btnRecord.on('touchstart',function(event){
event.preventDefault();
startTime=newDate().getTime();
//延时后录音,避免误操作
recordTimer=setTimeout(function(){
wx.startRecord({
success:function(){
localStorage.rainAllowRecord='true';
//style="display:block"
$(".voice_icon").css("display","block");
},
cancel:function(){
layer.open({
content:'用户拒绝了录音授权',
btn:'确定',
shadeClose:false,
});
}
});
},300);
}).on('touchend',function(event){
event.preventDefault();
//间隔太短
if(newDate().getTime()-startTime<300){
startTime=0;
//不录音
clearTimeout(recordTimer);
}else{//松手结束录音
wx.stopRecord({
success:function(res){
$(".voice_icon").css("display","none");
voice.localId=res.localId;
//上传到服务器
uploadVoice();
},
fail:function(res){
//alert(JSON.stringify(res));
layer.open({
content:JSON.stringify(res),
btn:'确定',
shadeClose:false,
});
}
});
}
});
});
},
error:function(){}
})
上传语音的方法
functionuploadVoice(){
//调用微信的上传录音接口把本地录音先上传到微信的服务器
//不过,微信只保留3天,而我们需要长期保存,我们需要把资源从微信服务器下载到自己的服务器
wx.uploadVoice({
localId:voice.localId,//需要上传的音频的本地ID,由stopRecord接口获得
isShowProgressTips:1,//默认为1,显示进度提示
success:function(res){
//alert(JSON.stringify(res));
//把录音在微信服务器上的id(res.serverId)发送到自己的服务器供下载。
voice.serverId=res.serverId;
$.ajax({
url:'/QyhSpeech/DownLoadVoice',
type:'post',
data:{serverId:res.serverId,Id:Id},
dataType:"json",
success:function(data){
if(data.Result==true&&data.ResultCode==1){
layer.open({
content:"录音上传完成!",//data.Message
btn:'确定',
shadeClose:false,
yes:function(index){
window.location.href=window.location.href;
}
});
}
else{
layer.open({
content:data.Message,
btn:'确定',
shadeClose:false,
});
}
},
error:function(xhr,errorType,error){
layer.open({
content:error,
btn:'确定',
shadeClose:false,
});
}
});
}
});
}
后台调用的方法 需要一个ffmpeg.exe自行下载
//下载语音并且转换的方法
privatestringGetVoicePath(stringvoiceId,stringaccess_token)
{
stringvoice="";
try
{
Log.Debug("access_token:",access_token);
//调用downloadmedia方法获得downfile对象
DownloadFiledownFile=WeiXin.DownloadMedia(voiceId,access_token);
if(downFile.Stream!=null)
{
stringfileName=Guid.NewGuid().ToString();
//生成amr文件
stringamrPath=Server.MapPath("~/upload/audior/");
if(!Directory.Exists(amrPath))
{
Directory.CreateDirectory(amrPath);
}
stringamrFilename=amrPath+fileName+".amr";
//varss=GetAMRFileDuration(amrFilename);
//Log.Debug("ss",ss.ToString());
using(FileStreamfs=newFileStream(amrFilename,FileMode.Create))
{
byte[]datas=newbyte[downFile.Stream.Length];
downFile.Stream.Read(datas,0,datas.Length);
fs.Write(datas,0,datas.Length);
}
//转换为mp3文件
stringmp3Path=Server.MapPath("~/upload/audio/");
if(!Directory.Exists(mp3Path))
{
Directory.CreateDirectory(mp3Path);
}
stringmp3Filename=mp3Path+fileName+".mp3";
AudioHelper.ConvertToMp3(Server.MapPath("~/ffmpeg/"),amrFilename,mp3Filename);
voice=fileName;
Log.Debug("voice:",voice);
}
}
catch{}
returnvoice;
}
调用GetVoicePath
//下载微信语音文件
publicJsonResultDownLoadVoice()
{
varfile="";
try
{
varserverId=Request["serverId"];//文件的serverId
file=GetVoicePath(serverId,CacheHelper.GetAccessToken());
returnJson(newResultJson{Message=file,Result=true,ResultCode=1});
}
catch(Exceptionex)
{
returnJson(newResultJson{Message=ex.Message,Result=false,ResultCode=0});
}
}
AudioHelper类
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Text.RegularExpressions;
usingSystem.Threading;
namespaceEYO.Common
{
///
///声音帮助类
///
publicsealedclassAudioHelper
{
privateconststringFfmpegUsername="ffmpeg";
privateconststringFfmpegPassword="it4pl803";
///
///音频转换
///
///ffmpeg文件目录
///源文件
///目标文件
///
publicstaticstringConvertToMp3(stringffmpegPath,stringsoruceFilename,stringtargetFileName)
{
//stringcmd=ffmpegPath+@"\ffmpeg.exe-i"+soruceFilename+""+targetFileName;
stringcmd=ffmpegPath+@"\ffmpeg.exe-i"+soruceFilename+"-ar44100-ab128k"+targetFileName;
returnConvertWithCmd(cmd);
}
privatestaticstringConvertWithCmd(stringcmd)
{
try
{
System.Diagnostics.Processprocess=newSystem.Diagnostics.Process();
process.StartInfo.FileName="cmd.exe";
process.StartInfo.UseShellExecute=false;
process.StartInfo.CreateNoWindow=true;
process.StartInfo.RedirectStandardInput=true;
process.StartInfo.RedirectStandardOutput=true;
process.StartInfo.RedirectStandardError=true;
process.Start();
process.StandardInput.WriteLine(cmd);
process.StandardInput.AutoFlush=true;
Thread.Sleep(1000);
process.StandardInput.WriteLine("exit");
process.WaitForExit();
stringoutStr=process.StandardOutput.ReadToEnd();
process.Close();
returnoutStr;
}
catch(Exceptionex)
{
return"error"+ex.Message;
}
}
}
}
文中标记红色的需要以下一个类库放在文中最后链接里面到时候直接放到项目里面即可(我也是找到)
总结
以上所述是小编给大家介绍的微信语音上传下载功能实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!