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";      }  }