search
HomeBackend DevelopmentPHP TutorialDetailed 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 = $(&#39;#record&#39;);
var startTime = 0;
var recordTimer = 300;
// 发语音
$.ajax({
  url: &#39;url请求需要微信的一些东西 下面success就是返回的东西&#39;,
  type: &#39;get&#39;,
  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(&#39;touchstart&#39;, function (event) {
        event.preventDefault();
        startTime = new Date().getTime();
        // 延时后录音,避免误操作
        recordTimer = setTimeout(function () {
          wx.startRecord({
            success: function () {
              localStorage.rainAllowRecord = &#39;true&#39;;
              //style="display:block"
              $(".voice_icon").css("display", "block");
            },
            cancel: function () {
              layer.open({
                content: &#39;用户拒绝了录音授权&#39;,
                btn: &#39;确定&#39;,
                shadeClose: false,
              });
            }
          });
        }, 300);
      }).on(&#39;touchend&#39;, 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: &#39;确定&#39;,
                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: &#39;/QyhSpeech/DownLoadVoice&#39;,
          type: &#39;post&#39;,
          data: { serverId: res.serverId, Id: Id },
          dataType: "json",
          success: function (data) {
            if (data.Result == true && data.ResultCode == 1) {
              layer.open({
                content: "录音上传完成!",//data.Message
                btn: &#39;确定&#39;,
                shadeClose: false,
                yes: function (index) {
                  window.location.href = window.location.href;
                }
              });
            }
            else {
              layer.open({
                content: data.Message,
                btn: &#39;确定&#39;,
                shadeClose: false,
              });
            }
          },
          error: function (xhr, errorType, error) {
            layer.open({
              content: error,
              btn: &#39;确定&#39;,
              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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何在PHP中实现SEO优化如何在PHP中实现SEO优化May 20, 2023 pm 01:30 PM

随着互联网的发展,SEO(SearchEngineOptimization,搜索引擎优化)已经成为了网站优化的重要一环。如果您想要使您的PHP网站在搜索引擎中获得更高的排名,就需要对SEO的内容有一定的了解了。本文将会介绍如何在PHP中实现SEO优化,内容包括网站结构优化、网页内容优化、外部链接优化,以及其他相关的优化技巧。一、网站结构优化网站结构对于S

如何在PHP中实现ERP系统如何在PHP中实现ERP系统May 20, 2023 pm 06:21 PM

随着电子商务和企业管理的发展,许多企业开始寻找更好的方法来处理其日常业务流程。ERP系统是一种能够整合企业各种业务流程的软件工具。它提供了全面的功能,包括生产、销售、采购、库存、财务等方面,帮助企业提高效率、控制成本和提高客户满意度。而在PHP编程语言中,也能够实现ERP系统,这就需要我们掌握一些基本的知识和技术。下面,我们将深入探讨如何在PHP中实现ERP

如何在PHP中实现CRM系统如何在PHP中实现CRM系统May 20, 2023 pm 12:31 PM

随着企业的发展,客户管理变得越来越重要。为了提高客户满意度和忠诚度,越来越多的企业采用客户关系管理系统(CRM)来帮助其管理客户关系。而PHP是一种流行的编程语言,因其简单易学、灵活和强大而被广泛应用于Web开发。那么,如何在PHP中实现CRM系统呢?本文将为您介绍实现CRM系统的步骤和技巧。Step1:需求分析在开始开发CRM系统之前,您需要进行需求分析

在PHP中如何实现物联网开发?在PHP中如何实现物联网开发?May 12, 2023 am 11:51 AM

随着物联网技术的发展和普及,越来越多的应用场景需要使用PHP语言进行物联网开发。PHP作为一种广泛应用于Web开发的脚本语言,它的易学易用、开发速度快、可扩展性强等特点,使其成为开发物联网应用的一种优秀选择。本文将介绍在PHP中实现物联网开发的常用技术和方法。一、传输协议和数据格式物联网设备通常使用TCP/IP或UDP协议进行数据传输,而HTTP协议是一个优

如何在PHP中实现轮播图如何在PHP中实现轮播图May 22, 2023 am 08:25 AM

随着互联网的发展,轮播图已经成为了网页设计中必不可少的一部分。在很多网页中,轮播图经常被用作展示企业文化、最新产品或是推广活动等场景。本篇文章将会分享如何使用PHP来实现轮播图的功能。一、轮播图的概念轮播图是网页中一种常见的视觉效果,一般由多个图片组成,在页面中自动或手动进行切换,展示多个内容。可以添加符合业务要求的动画效果,有助于引起用户的关注和提高网站的

如何在PHP中实现验证码如何在PHP中实现验证码May 20, 2023 am 11:31 AM

随着互联网的不断发展,越来越多的网站需要使用验证码来保证安全性。验证码是一种借助人类能力而无法被计算机破解的认证技术,广泛应用于网站注册、登录、找回密码等功能中。下面将介绍如何使用PHP实现验证码功能。一、生成验证码图片验证码图片的生成是验证码功能的核心,需要生成一个随机字符,并将其渲染为图像展示给用户。在PHP中,可以使用GD库来生成图片。GD库是一种用于

在PHP中如何实现智能合约?在PHP中如何实现智能合约?May 12, 2023 am 08:09 AM

智能合约(SmartContract)是一种基于区块链的自动化交易程序,可以实现自动化执行、验证和执行交易。智能合约可以减少交易中的人为干扰,提高交易的安全性和效率。在不同的区块链中,智能合约的实现方式略有不同。本文将介绍在PHP中如何实现智能合约。PHP是一种广泛使用的编程语言,特别适合Web开发。PHP有着成熟的开源生态系统,以及许多可靠的框架和库。在

如何在PHP中实现管家婆系统?如何在PHP中实现管家婆系统?May 12, 2023 am 08:12 AM

管家婆系统在现代企业管理中扮演着重要的角色,它不仅仅能够有效地提高企业的工作效率,还可以大大提高了企业的生产力和竞争力。与此同时,PHP作为一种广泛使用的动态脚本语言,也受到了许多企业的青睐。接下来,我们将探讨如何在PHP中实现管家婆系统,以提高企业的管理效率。一、了解管家婆系统管家婆系统是一种企业管理软件,主要用于管理公司的财务、销售、采购、仓库、人力资源

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools