目录

微信小程序实现录音上传

微信小程序实现录音上传

微信小程序实现录音上传

准备

开始

打开微信开发者工具

项目->新建项目

选择小程序

https://i-blog.csdnimg.cn/blog_migrate/abcc2eee08d1f00e95c955667cb7e145.png

appid是在微信公众平台申请的。

新建完成后,项目自带有模板。结构如图。

https://i-blog.csdnimg.cn/blog_migrate/0d8cf27faaa6575f3c421956c1b626e5.png

audio是我新建的。其余都是项目生成的。

wxml文件相当于html,wxss相当于css文件,json里可以方配置或者临时数据之类的。

在audio.wxml中添加开始录制按钮。

<!--pages/audio/audio.wxml-->
<view class="container">
  <button bindtap='record'>开始录音</button>
  <button bindtap='upload'>开始上传</button>  
  <text>pages/audio/audio.wxml</text>
</view>

对应的js文件下

Page({
  data: {
    tmpfile:'',
    time:''
  },
  record: function(e){
    var that = this;
    const starttime = Date.now();
    this.recorderManager = wx.getRecorderManager();
    this.recorderManager.onError(function(res){
      console.log(res)//错误信息自己判断
    })
    this.recorderManager.onStop(function(res){
      that.setData({
        tmpfile: res.tempFilePath,
        time: Date.now() - starttime,
      })
    })
    this.recorderManager.start({
      format:"mp3"
    })
    setTimeout(function(){
      that.recorderManager.stop();
    },10000);
  },
  stopRecord:function(e){
    console.log("stop")
    this.recorderManager.stop();
  },
  upload:function(){
    console.log("开始上传",this.data.time)
    wx.uploadFile({
      filePath: this.data.tmpfile, //录音文件
      name: 'name',
      url: '后台接口',
      format:{
        audio_ms: this.data.time,//时间长
      }
    })
  }
})

注:wx.stopRecord(Object object) 和 wx.startRecord(Object object) 从基础库 1.6.0 开始,接口停止维护。