小程序實現錄音上傳


首先我們先看一下微信小程序的API

https://developers.weixin.qq.com/miniprogram/dev/api/getRecorderManager.html?search-key=%E5%BD%95%E9%9F%B3

這里有關於小程序錄音的一些基本配置,

index.wxml:

1 <view class='progress_box' bindtap='openRecording' style="display:{{openRecordingdis}}">
2         <view class="progress_bgs">
3           <view class="progress_bg">
4             <image class="progress_img" src='../../../images/SubjectInformation/luyin.png'></image>
5           </view>
6         </view>
7 </view>

index.wxss:

 1 .topicRecording {
 2   float: left;
 3   width: 40%;
 4   height: 100%;
 5   position: relative;
 6 }
 7  
 8  
 9 .progress_box {
10   width: 130rpx;
11   height: 130rpx;
12   margin-left: -65rpx;
13   position: absolute;
14   bottom: 0;
15   left: 50%;
16   display: flex;
17   align-items: center;
18   justify-content: center;
19   background: #ccc;
20   border-radius: 50%;
21 }
22  
23 .progress_bgs {
24   width: 114rpx;
25   height: 114rpx;
26   background: #fff;
27   border-radius: 50%;
28   margin: 9rpx;
29 }
30  
31 .progress_bg {
32   width: 106rpx;
33   height: 106rpx;
34   margin: 5rpx;
35   position: absolute;
36   background: #444;
37   border-radius: 50%;
38 }
39 
40 .progress_img {
41   width: 82rpx;
42   height: 82rpx;
43   border-radius: 50%;
44   margin: 12rpx;
45 }

index.js:

  1 Page({
  2   data: {
  3     openRecordingdis: "block",//錄音圖片的不同
  4     shutRecordingdis: "none",//錄音圖片的不同
  5     recordingTimeqwe:0,//錄音計時
  6     setInter:""//錄音名稱
  7   },
  8  
  9    //錄音計時器
 10   recordingTimer:function(){
 11     var that = this;
 12     //將計時器賦值給setInter
 13     that.data.setInter = setInterval(
 14       function () {
 15         var time = that.data.recordingTimeqwe + 1;
 16         that.setData({
 17           recordingTimeqwe: time
 18         })
 19       }
 20       , 1000); 
 21   },
 22  
 23  
 24   //開始錄音
 25   openRecording: function() {
 26     var that = this;
 27     wx.getSystemInfo({
 28       success: function(res) {
 29         that.setData({
 30           shutRecordingdis: "block",
 31           openRecordingdis: "none"
 32         })
 33       }
 34     })
 35     const options = {
 36       duration: 60000, //指定錄音的時長,單位 ms,最大為10分鍾(600000),默認為1分鍾(60000)
 37       sampleRate: 16000, //采樣率
 38       numberOfChannels: 1, //錄音通道數
 39       encodeBitRate: 96000, //編碼碼率
 40       format: 'mp3', //音頻格式,有效值 aac/mp3
 41       frameSize: 50, //指定幀大小,單位 KB
 42     }
 43     //開始錄音計時   
 44     that.recordingTimer();
 45     //開始錄音
 46     recorderManager.start(options);
 47     recorderManager.onStart(() => {
 48       console.log('。。。開始錄音。。。')
 49     });
 50     //錯誤回調
 51     recorderManager.onError((res) => {
 52       console.log(res);
 53     })
 54   },
 55  
 56   //結束錄音
 57   shutRecording: function() {
 58     var that = this;
 59     wx.getSystemInfo({
 60       success: function(res) {
 61         that.setData({
 62           shutRecordingdis: "none",
 63           openRecordingdis: "block"
 64         })
 65       }
 66     })
 67     recorderManager.stop();
 68     recorderManager.onStop((res) => {
 69       console.log('。。停止錄音。。', res.tempFilePath)
 70       const {tempFilePath} = res;
 71       //結束錄音計時  
 72       clearInterval(that.data.setInter);
 73       //上傳錄音
 74       wx.uploadFile({
 75         url: appURL + '/wx_SubjectInformation/wx_SubjectRecordKeeping.do',//這是你自己后台的連接
 76         filePath: tempFilePath,
 77         name:"file",//后台要綁定的名稱
 78         header: {
 79           "Content-Type": "multipart/form-data"
 80         },
 81         //參數綁定
 82         formData:{
 83           recordingtime: that.data.recordingTimeqwe,
 84           topicid: that.data.topicid,
 85           userid:1,
 86           praisepoints:0
 87         },
 88         success:function(ress){
 89           console.log(res);
 90           wx.showToast({
 91             title: '保存完成',
 92             icon:'success',
 93             duration:2000
 94           })
 95         },
 96         fail: function(ress){
 97           console.log("。。錄音保存失敗。。");
 98         }
 99       })
100     })
101   },
102  
103   //錄音播放
104   recordingAndPlaying: function(eve) {
105     wx.playBackgroundAudio({
106       //播放地址
107       dataUrl: '' + eve.currentTarget.dataset.gid + ''
108     })
109   },
110  
111 })

上傳服務

 1 @RequestMapping(value = "/wx_SubjectRecordKeeping", produces = "application/json")
 2     @ResponseBody
 3     public Object wx_SubjectRecordKeeping(HttpServletRequest request,
 4             @RequestParam("file") MultipartFile files, String recordingtime,
 5             int topicid,int userid,int praisepoints) {
 6         // 構建上傳目錄路徑
 7         // request.getServletContext().getRealPath("/upload");
 8         String uploadPath = 你自己保存音頻的URL;
 9         // 如果目錄不存在就創建
10         File uploadDir = new File(uploadPath);
11         if (!uploadDir.exists()) {
12             uploadDir.mkdir();
13         }
14         // 獲取文件的 名稱.擴展名
15         String oldName = files.getOriginalFilename();
16         String extensionName = "";
17         // 獲取原來的擴展名
18         if ((oldName != null) && (oldName.length() > 0)) {
19             int dot = oldName.lastIndexOf('.');
20             if ((dot > -1) && (dot < (oldName.length() - 1))) {
21                 extensionName = oldName.substring(dot);
22             }
23         }
24         // 構建文件名稱
25         String fileName = System.currentTimeMillis() + "_" + System.nanoTime()
26                 + extensionName;
27         // 獲取
28         String[] fileType = { ".CD", ".WAVE", ".AIFF", ".AU", ".MPEG", ".MP3",
29                 ".MPEG-4", ".MIDI", ".WMA", ".RealAudio", ".VQF", ".OggVorbis",
30                 ".AMR" };
31         List<String> fileTyepLists = Arrays.asList(fileType);
32         int fileTypeOnCount = 0;
33         for (String fileTyepListss : fileTyepLists) {
34             if (fileTyepListss.equalsIgnoreCase(extensionName)) {
35                 // -----如果是音頻文件的話
36                 // 構建文件路徑
37                 String filePath = uploadPath + File.separator + fileName;
38                 // 保存文件
39                 try {
40                     FileUtils.writeByteArrayToFile(new File(filePath),
41                             files.getBytes());
42                 } catch (Exception e) {
43                     e.printStackTrace();
44                 }
45             } else {
46                 fileTypeOnCount++;
47             }
48         }
49         if (fileTypeOnCount == fileTyepLists.size()) {
50             // 不是音頻文件
51             return false;
52         }
53         return false;
54             }    

效果圖

點擊開始錄音、錄完后點擊結束錄音

錄音成功后的返回

錄制的音頻文件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM