微信語(yǔ)音上傳 下載功能實(shí)例代碼
假如現(xiàn)在有一個(gè)按鈕
<div class="inp_btn voice_btn active" id="record"> 按住 說(shuō)話 </div>
下面就是調(diào)用微信jssdk的方法
var recorder; var btnRecord = $('#record'); var startTime = 0; var recordTimer = 300; // 發(fā)語(yǔ)音 $.ajax({ url: 'url請(qǐng)求需要微信的一些東西 下面success就是返回的東西', type: 'get', data: { url: url }, success: function (data) { var json = $.parseJSON(data); //alert(json); //假設(shè)已引入微信jssdk?!局С质褂?AMD/CMD 標(biāo)準(zhǔn)模塊加載方法加載】 wx.config({ debug: false, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會(huì)在客戶端alert出來(lái),若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會(huì)通過(guò)log打出,僅在pc端時(shí)才會(huì)打印。 appId: json.appid, // 必填,公眾號(hào)的唯一標(biāo)識(shí) timestamp: json.timestamp, // 必填,生成簽名的時(shí)間戳 nonceStr: json.nonceStr, // 必填,生成簽名的隨機(jī)串 signature: json.signature, // 必填,簽名,見(jiàn)附錄1 jsApiList: [ "startRecord", "stopRecord", "onVoiceRecordEnd", "playVoice", "pauseVoice", "stopVoice", "onVoicePlayEnd", "uploadVoice", "downloadVoice", ] // 必填,需要使用的JS接口列表,所有JS接口列表見(jiàn)附錄2 }); wx.ready(function () { btnRecord.on('touchstart', function (event) { event.preventDefault(); startTime = new Date().getTime(); // 延時(shí)后錄音,避免誤操作 recordTimer = setTimeout(function () { wx.startRecord({ success: function () { localStorage.rainAllowRecord = 'true'; //style="display:block" $(".voice_icon").css("display", "block"); }, cancel: function () { layer.open({ content: '用戶拒絕了錄音授權(quán)', btn: '確定', shadeClose: false, }); } }); }, 300); }).on('touchend', function (event) { event.preventDefault(); // 間隔太短 if (new Date().getTime() - startTime < 300) { startTime = 0; // 不錄音 clearTimeout(recordTimer); } else { // 松手結(jié)束錄音 wx.stopRecord({ success: function (res) { $(".voice_icon").css("display", "none"); voice.localId = res.localId; // 上傳到服務(wù)器 uploadVoice(); }, fail: function (res) { //alert(JSON.stringify(res)); layer.open({ content: JSON.stringify(res), btn: '確定', shadeClose: false, }); } }); } }); }); }, error: function () { } })
上傳語(yǔ)音的方法
function uploadVoice() { //調(diào)用微信的上傳錄音接口把本地錄音先上傳到微信的服務(wù)器 //不過(guò),微信只保留3天,而我們需要長(zhǎng)期保存,我們需要把資源從微信服務(wù)器下載到自己的服務(wù)器 wx.uploadVoice({ localId: voice.localId, // 需要上傳的音頻的本地ID,由stopRecord接口獲得 isShowProgressTips: 1, // 默認(rèn)為1,顯示進(jìn)度提示 success: function (res) { // alert(JSON.stringify(res)); //把錄音在微信服務(wù)器上的id(res.serverId)發(fā)送到自己的服務(wù)器供下載。 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, }); } }); } }); }
后臺(tái)調(diào)用的方法 需要一個(gè)ffmpeg.exe自行下載
//下載語(yǔ)音并且轉(zhuǎn)換的方法 private string GetVoicePath(string voiceId, string access_token) { string voice = ""; try { Log.Debug("access_token:", access_token); //調(diào)用downloadmedia方法獲得downfile對(duì)象 DownloadFile downFile = WeiXin.DownloadMedia(voiceId, access_token); if (downFile.Stream != null) { string fileName = Guid.NewGuid().ToString(); //生成amr文件 string amrPath = Server.MapPath("~/upload/audior/"); if (!Directory.Exists(amrPath)) { Directory.CreateDirectory(amrPath); } string amrFilename = amrPath + fileName + ".amr"; //var ss = GetAMRFileDuration(amrFilename); //Log.Debug("ss", ss.ToString()); using (FileStream fs = new FileStream(amrFilename, FileMode.Create)) { byte[] datas = new byte[downFile.Stream.Length]; downFile.Stream.Read(datas, 0, datas.Length); fs.Write(datas, 0, datas.Length); } //轉(zhuǎn)換為mp3文件 string mp3Path = Server.MapPath("~/upload/audio/"); if (!Directory.Exists(mp3Path)) { Directory.CreateDirectory(mp3Path); } string mp3Filename = mp3Path + fileName + ".mp3"; AudioHelper.ConvertToMp3(Server.MapPath("~/ffmpeg/"), amrFilename, mp3Filename); voice = fileName; Log.Debug("voice:", voice); } } catch { } return voice; }
調(diào)用GetVoicePath
//下載微信語(yǔ)音文件 public JsonResult DownLoadVoice() { var file = ""; try { var serverId = Request["serverId"];//文件的serverId file = GetVoicePath(serverId, CacheHelper.GetAccessToken()); return Json(new ResultJson { Message = file, Result = true, ResultCode = 1 }); } catch (Exception ex) { return Json(new ResultJson { Message = ex.Message, Result = false, ResultCode = 0 }); } }
AudioHelper類
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace EYO.Common { /// <summary> /// 聲音幫助類 /// </summary> public sealed class AudioHelper { private const string FfmpegUsername = "ffmpeg"; private const string FfmpegPassword = "it4pl803"; /// <summary> /// 音頻轉(zhuǎn)換 /// </summary> /// <param name="ffmpegPath">ffmpeg文件目錄</param> /// <param name="soruceFilename">源文件</param> /// <param name="targetFileName">目標(biāo)文件</param> /// <returns></returns> public static string ConvertToMp3(string ffmpegPath, string soruceFilename, string targetFileName) { //string cmd = ffmpegPath + @"\ffmpeg.exe -i " + soruceFilename + " " + targetFileName; string cmd = ffmpegPath + @"\ffmpeg.exe -i " + soruceFilename + " -ar 44100 -ab 128k " + targetFileName; return ConvertWithCmd(cmd); } private static string ConvertWithCmd(string cmd) { try { System.Diagnostics.Process process = new System.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(); string outStr = process.StandardOutput.ReadToEnd(); process.Close(); return outStr; } catch (Exception ex) { return "error" + ex.Message; } } } }
文中標(biāo)記紅色的需要以下一個(gè)類庫(kù) 放在文中最后鏈接里面 到時(shí)候直接放到項(xiàng)目里面即可(我也是找到)
總結(jié)
以上所述是小編給大家介紹的微信語(yǔ)音上傳 下載功能實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
利用FastReport傳遞圖片參數(shù)在報(bào)表上展示簽名信息的實(shí)現(xiàn)方法
這篇文章主要介紹了利用FastReport傳遞圖片參數(shù)在報(bào)表上展示簽名信息,其中主要注意的是,我們傳遞的圖片數(shù)據(jù)需要采用Base64String的格式才能正常傳遞和展示,本文通過(guò)圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10ASP.NET動(dòng)態(tài)生成靜態(tài)頁(yè)面的實(shí)例代碼
生成靜態(tài)頁(yè)有很多好處,可以緩解服務(wù)器壓力、方便搜索網(wǎng)站搜索等等,下面介紹一下生成靜態(tài)頁(yè)的實(shí)例代碼,有需要的朋友可以參考一下2013-07-07C#反射技術(shù)的簡(jiǎn)單操作(讀取和設(shè)置類的屬性)
反射的作用想必大家都知道了吧,少量屬性的自動(dòng)化操作手動(dòng)添加幾下當(dāng)然是沒(méi)有問(wèn)題的,但是屬性數(shù)量較多的時(shí)候敲起這些繁鎖的代碼可以困了,再說(shuō)對(duì)擴(kuò)展和維護(hù)性造成很多的不遍,以下代碼中如不能直接使用請(qǐng)?zhí)砑觰sing System.Text;的引用。2011-01-01asp.net多選項(xiàng)卡頁(yè)面的創(chuàng)建及使用方法
看了很多朋友還不會(huì)創(chuàng)建多選項(xiàng)卡的頁(yè)面,特地總結(jié)了一下用法,看一遍就會(huì)了,感興趣的朋友可以參考下2013-01-01ASP.NET動(dòng)態(tài)加載用戶控件的實(shí)現(xiàn)方法
動(dòng)態(tài)加載用戶控件的方法,用asp.net的朋友推薦2008-10-10