假如現在有一個按鈕 <div class="inp_btn voice_btn active" id="record"> 按住 說話 </div> 下麵就是調用微信jssdk的方法 var recorder; var btnRecord = $('#record'); var startTime = ...
假如現在有一個按鈕
<div class="inp_btn voice_btn active" id="record"> 按住 說話 </div>
下麵就是調用微信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; } } } }
文中需要 DownloadFile downFile = WeiXin.DownloadMedia(voiceId, access_token); 需要一個類庫 到時候直接放到項目裡面即可(我也是找到)
http://files.cnblogs.com/files/hbh123/Loogn.WeiXinSDK.rar