SpringBoot开发案例之微信小程序录音上传

  • 2019 年 12 月 9 日
  • 筆記

前言

书接上回的《SpringBoot开发案例之微信小程序文件上传》,正常的业务流程是,口语测评需要学生通过前端微信小程序录入一段音频,通过调用第三方音频处理服务商进行评分,然后服务端对原始录音、标准录音以及评分信息进行存储,最终呈现给学生并用于复看以及复读。

微信端

index.wxml:

<button bindtap="start" class='btn'>开始录音</button>  <button bindtap="pause" class='btn'>暂停录音</button>  <button bindtap="stop" class='btn'>停止录音</button>  <button bindtap="play" class='btn'>播放录音</button>  <button bindtap="upload" class='btn'>上传录音</button>

index.wxss:

.btn{    margin-top: 10rpx;  }

index.js:

//录音管理  const recorderManager = wx.getRecorderManager()  //音频组件控制  const innerAudioContext = wx.createInnerAudioContext()  var tempFilePath;  Page({    data: {      },    //开始录音的时候    start: function () {      const options = {        duration: 10000,//指定录音的时长,单位 ms        sampleRate: 16000,//采样率        numberOfChannels: 1,//录音通道数        encodeBitRate: 96000,//编码码率        format: 'mp3',//音频格式,有效值 aac/mp3        frameSize: 50,//指定帧大小,单位 KB      }      //开始录音      recorderManager.start(options);      recorderManager.onStart(() => {        console.log('recorder start')      });      //错误回调      recorderManager.onError((res) => {        console.log(res);      })    },    //暂停录音    pause: function () {      recorderManager.onPause();      console.log('暂停录音')    },    //停止录音    stop: function () {      recorderManager.stop();      recorderManager.onStop((res) => {        this.tempFilePath = res.tempFilePath;        console.log('停止录音', res.tempFilePath)        const { tempFilePath } = res      })    },    //播放声音    play: function () {      innerAudioContext.autoplay = true      innerAudioContext.src = this.tempFilePath,        innerAudioContext.onPlay(() => {          console.log('开始播放')        })      innerAudioContext.onError((res) => {        console.log(res.errMsg)        console.log(res.errCode)      })      },    //上传录音    upload:function(){      wx.uploadFile({        url: "https://xxx.com/fileUpload",//演示域名、自行配置        filePath: this.tempFilePath,        name: 'file',        header: {          "Content-Type": "multipart/form-data"        },        formData:        {          userId: 12345678 //附加信息为用户ID        },        success: function (res) {          console.log(res);          wx.showToast({            title: '上传成功',            icon: 'success',            duration: 2000          })        },        fail: function (res) {          console.log(res);        },        complete: function (res) {          }      })    },    onLoad: function () {      },  })

上传服务

/**   * 口语测试   * 创建者 柒   * 创建时间    2018年3月13日   */  @Api(tags ="口语测试接口")  @RestController  @RequestMapping("/test")  public class TestController {      private final static Logger LOGGER = LoggerFactory.getLogger(WechatController.class);      @Value("${web.upload.path}")      private String uploadPath;      @ApiOperation(value="上传文件(小程序)")      @PostMapping("/fileUpload")      public String upload(HttpServletRequest request, @RequestParam("file")MultipartFile[] files){          LOGGER.info("上传测试");          //多文件上传          if(files!=null && files.length>=1) {              BufferedOutputStream bw = null;              try {                  String fileName = files[0].getOriginalFilename();                  //判断是否有文件(实际生产中要判断是否是音频文件)                  if(StringUtils.isNoneBlank(fileName)) {                      //创建输出文件对象                      File outFile = new File(uploadPath + UUID.randomUUID().toString()+ FileUtil.getFileType(fileName));                      //拷贝文件到输出文件对象                      FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile);                  }              } catch (Exception e) {                  e.printStackTrace();              } finally {                  try {                      if(bw!=null) {bw.close();}                  } catch (IOException e) {                      e.printStackTrace();                  }              }          }          return "success";      }  }