欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信语音上传 下载功能实例代码

程序员文章站 2023-02-15 19:20:51
假如现在有一个按钮
按住 说话...

假如现在有一个按钮

<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;
      }
    }
  }
}

  文中标记红色的需要以下一个类库 放在文中最后链接里面 到时候直接放到项目里面即可(我也是找到)

总结

以上所述是小编给大家介绍的微信语音上传 下载功能实例代码,希望对大家有所帮助