Example code and voice example of the WeChat voice upload/download function

Source: Internet
Author: User

Example code of the voice upload/download function

Assume there is a button

<Div class = "inp_btn voice_btn active" id = "record"> hold down and talk </div>

The following describes how to call jssdk.

Var recorder; var btnRecord =$ ('# record'); var startTime = 0; var recordTimer = 300; // send voice $. ajax ({url: 'url request requires something success is returned ', type: 'get', data: {url: url}, success: function (data) {var json = $. parseJSON (data); // alert (json); // assume that jssdk has been introduced. [Supports loading using AMD/CMD standard modules] wx. config ({debug: false, // enable the debugging mode. The returned values of all called APIs are displayed in the client alert. To view the input parameters, you can open them on the pc, the parameter information is output through log and printed only on the pc end. AppId: json. appid, // required. timestamp, which is the unique identifier of the public account, is json. timestamp, // required. The signature timestamp nonceStr: json. nonceStr, // required. The random signature string signature: json. signature, // required, signature. For details, see Appendix 1 jsApiList: ["startRecord", "stopRecord", "onVoiceRecordEnd", "playVoice", "pauseVoice", "stopVoice ", "onVoicePlayEnd", "uploadVoice", "downloadVoice",] // required. List of JS interfaces to be used. For the list of all JS interfaces, see Appendix 2}); wx. ready (function () {btnRecord. on ('touchstart', function (event) {event. preventDefault (); startTime = new Date (). getTime (); // recording after delay to avoid misoperation recordTimer = setTimeout (function () {wx. startRecord ({success: function () {localStorage. rainAllowRecord = 'true'; // style = "display: block" $ (". voice_icon ").css (" display "," block ") ;}, cancel: function () {layer. open ({content: 'Recording Authorization denied by the user ', btn:' OK ', shadeClose: false,}) ;}) ;}, 300 );}). on ('touchend', function (event) {event. preventDefault (); // The interval is too short if (new Date (). getTime ()-startTime <300) {startTime = 0; // do not record clearTimeout (recordTimer);} else {// start recording wx. stopRecord ({success: function (res) {$ (". voice_icon ").css (" display "," none "); voice. localId = res. localId; // upload to the server uploadVoice () ;}, fail: function (res) {// alert (JSON. stringify (res); layer. open ({content: JSON. stringify (res), btn: 'OK', shadeClose: false,}) ;}}) ;}, error: function (){}})

 How to upload voice

Function uploadVoice () {// call the upload recording interface to upload the local recording to the server first // However, It is retained for only three days, and we need to save it for a long time, we need to download resources from the server to our server wx. uploadVoice ({localId: voice. localId, // The local ID of the audio to be uploaded. isShowProgressTips: 1 is obtained by the stopRecord interface. // The default value is 1. The progress prompt success: function (res) is displayed) {// alert (JSON. stringify (res); // id (res. serverId) is sent to your server for download. 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: "The recording has been uploaded! ", // Data. message btn: 'OK', shadeClose: false, yes: function (index) {window. location. href = window. location. href ;}}) ;}else {layer. open ({content: data. message, btn: 'OK', shadeClose: false,}) ;}}, error: function (xhr, errorType, error) {layer. open ({content: error, btn: 'OK', shadeClose: false ,});}});}});}

The method called in the background is downloaded by ffmpeg.exe.

// Download and convert the voice using private string GetVoicePath (string voiceId, string access_token) {string voice = ""; try {Log. debug ("access_token:", access_token); // call the downloadmedia method to obtain the downfile object DownloadFile downFile = WeiXin. downloadMedia (voiceId, access_token); if (downFile. stream! = Null) {string fileName = Guid. NewGuid (). ToString (); // generate the amr file 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);} // convert 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

// Download the voice file public JsonResult DownLoadVoice () {var file = ""; try {var serverId = Request ["serverId"]; // file 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> // audio help class /// </summary> public sealed class AudioHelper {private const string FfmpegUsername = "ffmpeg "; private const string FfmpegPassword = "it4pl803 "; /// <summary> /// audio conversion /// </summary> /// <param name = "ffmpegPath"> ffmpeg file directory </param> /// <param name = "soruceFilename"> source file </param> // <param name = "targetFileName"> target file </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 128 k" + 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 marked red in the text should be put in the last link of the text with the next class library, and then directly put it in the project (I also found it)

Summary

The above is the example code of the voice upload/download function introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.