侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

微信(小程序)  /  管理员 发布于 7年前   158

假如现在有一个按钮

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

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

总结

以上所述是小编给大家介绍的微信语音上传 下载功能实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!


  • 上一条:
    .NET微信扫码支付接入(模式二-NATIVE)
    下一条:
    使用微信PC端的截图dll库实现微信截图功能
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 微信模板消息改版后发送规则记录(微信订阅消息参数值内容限制说明)(1个评论)
    • 微信支付v3对接所需工具及命令(0个评论)
    • 2023年9月1日起:微信小程序必须备案才能上线运营(0个评论)
    • 腾讯官方客服回应了:微信好友上限约10000个!(1个评论)
    • 2023年做微信小程序的老铁注意:新增收费项、微信小程序获取手机号也收费了(2个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-10
    • 2018-01
    • 2020-03
    • 2021-06
    • 2021-10
    • 2022-03
    • 2023-02
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客