微信小程序之录音与播放

录音参考官方网址:

https://developers.weixin.qq.com/miniprogram/dev/api/RecorderManager.html

播放参考官方网址:

https://developers.weixin.qq.com/miniprogram/dev/api/InnerAudioContext.html

1、 .wxml文件

微信小程序之录音与播放_第1张图片

其中 isSpeaking 为true时,为正在录音,显示麦的动态图

微信小程序之录音与播放_第2张图片

2、 .wxss文件

微信小程序之录音与播放_第3张图片

3、  .js文件

(1)先声明语音识别管理器和音频管理器

(2)声明所需参数

微信小程序之录音与播放_第4张图片

(3)录音按钮按下方法

微信小程序之录音与播放_第5张图片

(4)录音按钮松开方法

jiesuluyin:function(e){
    console.log("结束录音")
    var that = this;
    recorderManager.stop(); //先停止录音
    this.setData({
      isSpeaking: false
    })
    recorderManager.onStop((res) => {  //监听录音停止的事件
      console.log("监听录音停止事件",res)
      if (res.duration < 1000) {
        wx.showToast({
          title: '录音时间太短'
        })
        return;
      } else {
        wx.showLoading({
          title: '发送中...',
        });

        var tempFilePath = res.tempFilePath; // 文件临时路径
        console.log("文件临时路径", tempFilePath)

        wx.uploadFile({
          url: '', //上传服务器的地址
          filePath: tempFilePath, //临时路径
          name: 'file',
          header: {
            contentType: "multipart/form-data", //按需求增加
          },
          formData: null,
          success: function (res) {
            console.log("上传成功")
            wx.hideLoading();
            that.setData({
              bofangurl: tempFilePath
            })
          },
          fail: function (err) {
            wx.hideLoading();
            console.log(err.errMsg);//上传失败
          }
        });
      }
    });
  },

(5)按下播放按钮方法

微信小程序之录音与播放_第6张图片

4、效果

微信小程序之录音与播放_第7张图片

点击播放按钮时可播放当前录音内容

代码可直接使用,按钮样式可自行修改

你可能感兴趣的:(微信小程序)