


Detailed explanation of the upload and download function of WeChat voice
This article mainly introduces the example code of WeChat voice upload and download function. Friends who need it can refer to it
If there is a button now
<p class="inp_btn voice_btn active" id="record"> 按住 说话 </p>
The following is the method of calling WeChat 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 () { } })
Method for uploading voice
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, }); } }); } }); }
Background call method You need a ffmpeg.exe to download by yourself
//下载语音并且转换的方法 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; }
Call 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 Class
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; } } } }
The ones marked in red in the article need to be placed in the last link in the article. Then you can put it directly into the project (I also found it)
The above is the detailed content of Detailed explanation of the upload and download function of WeChat voice. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

The superpeople game can be downloaded through the steam client. The size of this game is about 28G. It usually takes one and a half hours to download and install. Here is a specific download and installation tutorial for you! New method to apply for global closed testing 1) Search for "SUPERPEOPLE" in the Steam store (steam client download) 2) Click "Request access to SUPERPEOPLE closed testing" at the bottom of the "SUPERPEOPLE" store page 3) After clicking the request access button, The "SUPERPEOPLECBT" game can be confirmed in the Steam library 4) Click the install button in "SUPERPEOPLECBT" and download

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

As a convenient and practical network disk tool, Quark can help users easily obtain their favorite resources. What if you want to download a file locally? Let the editor tell you now, let’s learn it together! How to download Quark Network Disk to local sharing method 1. First open the Quark software, enter the homepage, and click the [Cloud Icon] on the lower right; 2. Then on the Quark Network Disk page, we click the [Document] function; 3. Then go to the document page, select the file you want to download, and click the [three-dot icon]; 4. After the final click, we click [Download] in the pop-up dialog box;

As an indispensable accompaniment to children's growth, Beilehu's children's songs have won the love of countless parents and children with their cheerful melody, vivid pictures and entertaining and educational content. In order to allow babies to enjoy the joy brought by children's songs anytime and anywhere, many parents hope to download Beilehu's children's songs to their mobile phones or tablets so that they can listen to their children at any time, but how to save Beilehu's children's songs? On your mobile phone, this tutorial will bring you a detailed introduction. Users who don’t understand it yet can come and read along with this article to learn more. Beilehu Nursery Rhymes Download Children's Songs Multi-Picture Tutorial: Open the software and select a children's song you want to download. The editor takes "Classic Children's Songs" as an example. 2. Click the "Download" button below the children's song star.

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.
