這篇文章主要介紹了微信語音上傳下載功能實例代碼,需要的朋友可以參考下
假如現在有一個按鈕
<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; }
r類別
//下载微信语音文件 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 }); } }
文中標記紅色的需要以下一個類別庫放在文中最後連結裡面到時候直接放到項目裡面即可(我也是找到)
以上是微信語音的上傳與下載功能實現詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

PHP仍然流行的原因是其易用性、靈活性和強大的生態系統。 1)易用性和簡單語法使其成為初學者的首選。 2)與web開發緊密結合,處理HTTP請求和數據庫交互出色。 3)龐大的生態系統提供了豐富的工具和庫。 4)活躍的社區和開源性質使其適應新需求和技術趨勢。

PHP和Python都是高層次的編程語言,廣泛應用於Web開發、數據處理和自動化任務。 1.PHP常用於構建動態網站和內容管理系統,而Python常用於構建Web框架和數據科學。 2.PHP使用echo輸出內容,Python使用print。 3.兩者都支持面向對象編程,但語法和關鍵字不同。 4.PHP支持弱類型轉換,Python則更嚴格。 5.PHP性能優化包括使用OPcache和異步編程,Python則使用cProfile和異步編程。

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP在現代化進程中仍然重要,因為它支持大量網站和應用,並通過框架適應開發需求。 1.PHP7提升了性能並引入了新功能。 2.現代框架如Laravel、Symfony和CodeIgniter簡化開發,提高代碼質量。 3.性能優化和最佳實踐進一步提升應用效率。

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

記事本++7.3.1
好用且免費的程式碼編輯器

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。