溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么實(shí)現(xiàn)一個微信語音上傳和下載功能

發(fā)布時間:2020-12-21 15:55:22 來源:億速云 閱讀:234 作者:Leah 欄目:開發(fā)技術(shù)

怎么實(shí)現(xiàn)一個微信語音上傳和下載功能?相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

假如現(xiàn)在有一個按鈕

<div class="inp_btn voice_btn active" id="record">
       按住 說話
     </div>

下面就是調(diào)用微信jssdk的方法

var recorder;
var btnRecord = $('#record');
var startTime = 0;
var recordTimer = 300;
// 發(fā)語音
$.ajax({
  url: 'url請求需要微信的一些東西 下面success就是返回的東西',
  type: 'get',
  data: { url: url },
  success: function (data) {
    var json = $.parseJSON(data);
    //alert(json);
    //假設(shè)已引入微信jssdk?!局С质褂?nbsp;AMD/CMD 標(biāo)準(zhǔn)模塊加載方法加載】
    wx.config({
      debug: false, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會通過log打出,僅在pc端時才會打印。
      appId: json.appid, // 必填,公眾號的唯一標(biāo)識
      timestamp: json.timestamp, // 必填,生成簽名的時間戳
      nonceStr: json.nonceStr, // 必填,生成簽名的隨機(jī)串
      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';
              //
              $(".voice_icon").css("display", "block");
            },
            cancel: function () {
              layer.open({
                content: '用戶拒絕了錄音授權(quán)',
                btn: '確定',
                shadeClose: false,
              });
            }
          });
        }, 300);
      }).on('touchend', function (event) {
        event.preventDefault();
        // 間隔太短
        if (new Date().getTime() - startTime < 300) {
          startTime = 0;
          // 不錄音
          clearTimeout(recordTimer);
        } else { // 松手結(jié)束錄音
          wx.stopRecord({
            success: function (res) {
              $(".voice_icon").css("display", "none");
              voice.localId = res.localId;
              // 上傳到服務(wù)器
              uploadVoice();
            },
            fail: function (res) {
              //alert(JSON.stringify(res));
              layer.open({
                content: JSON.stringify(res),
                btn: '確定',
                shadeClose: false,
              });
            }
          });
        }
      });
    });
  },
  error: function () { }
})

 上傳語音的方法 

function uploadVoice() {
    //調(diào)用微信的上傳錄音接口把本地錄音先上傳到微信的服務(wù)器
    //不過,微信只保留3天,而我們需要長期保存,我們需要把資源從微信服務(wù)器下載到自己的服務(wù)器
    wx.uploadVoice({
      localId: voice.localId, // 需要上傳的音頻的本地ID,由stopRecord接口獲得
      isShowProgressTips: 1, // 默認(rèn)為1,顯示進(jìn)度提示
      success: function (res) {
        // alert(JSON.stringify(res));
        //把錄音在微信服務(wù)器上的id(res.serverId)發(fā)送到自己的服務(wù)器供下載。
        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,
            });
          }
        });
      }
    });
  }

  后臺調(diào)用的方法     需要一個ffmpeg.exe自行下載

//下載語音并且轉(zhuǎn)換的方法
    private string GetVoicePath(string voiceId, string access_token)
    {
      string voice = "";
      try
      {
        Log.Debug("access_token:", access_token);
        //調(diào)用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);
          }
          //轉(zhuǎn)換為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;
    }

  調(diào)用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>
    /// 音頻轉(zhuǎn)換
    /// </summary>
    /// <param name="ffmpegPath">ffmpeg文件目錄</param>
    /// <param name="soruceFilename">源文件</param>
    /// <param name="targetFileName">目標(biāo)文件</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;
      }
    }
  }
}

  文中標(biāo)記紅色的需要以下一個類庫 放在文中最后鏈接里面 到時候直接放到項(xiàng)目里面即可(我也是找到)

看完上述內(nèi)容,你們掌握怎么實(shí)現(xiàn)一個微信語音上傳和下載功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI