假如現(xiàn)在有一個(gè)按鈕
<div class="inp_btn voice_btn active" id="record"> 按住 說話 </div>
下面就是調(diào)用微信jssdk的方法
var recorder;var btnRecord = $('#record');var startTime = 0;var recordTimer = 300;// 發(fā)語音$.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出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會(huì)通過log打出,僅在pc端時(shí)才會(huì)打印。 appId: json.appid, // 必填,公眾號(hào)的唯一標(biāo)識(shí) timestamp: json.timestamp, // 必填,生成簽名的時(shí)間戳 nonceStr: json.nonceStr, // 必填,生成簽名的隨機(jī)串 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 = 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 () { }})
上傳語音的方法
function uploadVoice() { //調(diào)用微信的上傳錄音接口把本地錄音先上傳到微信的服務(wù)器 //不過,微信只保留3天,而我們需要長期保存,我們需要把資源從微信服務(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自行下載
//下載語音并且轉(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
//下載微信語音文件 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è)類庫 放在文中最后鏈接里面 到時(shí)候直接放到項(xiàng)目里面即可(我也是找到)
總結(jié)
以上所述是小編給大家介紹的微信語音上傳 下載功能實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)VeVb武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選