這篇文章主要介紹了語音上傳 下載功能執行個體代碼,需要的朋友可以參考下
假如現在有一個按鈕
<p class="inp_btn voice_btn active" id="record"> 按住 說話 </p>
下面就是調用jssdk的方法
var recorder;var btnRecord = $('#record');var startTime = 0;var recordTimer = 300;// 發語音$.ajax({ url: 'url請求需要的一些東西 下面success就是返回的東西', type: 'get', data: { url: url }, success: function (data) { var json = $.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 = new Date().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 (new Date().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 () { }})
上傳語音的方法
function uploadVoice() { //調用的上傳錄音介面把本地錄音先上傳到的伺服器 //不過,只保留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自行下載
//下載語音並且轉換的方法 private string GetVoicePath(string voiceId, string access_token) { string voice = ""; try { Log.Debug("access_token:", access_token); //調用downloadmedia方法獲得downfile對象 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); } //轉換為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; }
調用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> /// 音頻轉換 /// </summary> /// <param name="ffmpegPath">ffmpeg檔案目錄</param> /// <param name="soruceFilename">源檔案</param> /// <param name="targetFileName">目標檔案</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; } } }}
文中標記紅色的需要以下一個類庫 放在文中最後連結裡面 到時候直接放到項目裡面即可(我也是找到)