最近在做小程序,需求有上傳錄音,并且上傳多條音頻成功后,可以播放,暫停。剛開始接到時(shí),感覺頭都大了。但是還好小程序文檔的api也很全面
1.上傳功能
image.png
<view bindtouchstart='sayVideo' bindtouchend="sayVideoEnd">按住說(shuō)話</view >
2.用觸控事件,來(lái)監(jiān)聽按住說(shuō)話。松開發(fā)送。首先要獲取全局唯一的錄音管理器 RecorderManager。參考文檔
(https://developers.weixin.qq.com/miniprogram/dev/api/RecorderManager.html)
const recorderManager = wx.getRecorderManager();
//監(jiān)聽事件 按住說(shuō)話
sayVideo: function(e) {
//按住說(shuō)話
sayVideo: function(e) {
var that = this;
const options = {
duration: 60000,
sampleRate: 16000,
numberOfChannels: 1,
encodeBitRate: 96000,
format: 'mp3',
frameSize: 50
};
if (this.data.status != 2) {
//沒(méi)有授權(quán)
wx.authorize({
scope: 'scope.record',
success() {
console.log("錄音授權(quán)成功");
//第一次成功授權(quán)后 狀態(tài)切換為2
that.setData({
status: 2,
})
},
fail() {
wx.openSetting({
success: (res) => {
console.log(res.authSetting);
if (!res.authSetting['scope.record']) {
//未設(shè)置錄音授權(quán)
console.log("未設(shè)置錄音授權(quán)");
wx.showModal({
title: '提示',
content: '您未授權(quán)錄音,功能將無(wú)法使用',
showCancel: false,
success: function(res) {},
});
} else {
//第二次才成功授權(quán)
console.log("設(shè)置錄音授權(quán)成功");
that.setData({
status: 2,
})
recorderManager.start(options);
}
},
fail: function() {
console.log("授權(quán)設(shè)置錄音失敗");
}
})
}
});
}else{
recorderManager.start(options);
}
}
3.松開上傳
//松開
sayVideoEnd: function (e) {
var that= this;
recorderManager.stop(); //先停止錄音
recorderManager.onStop((res) => { //監(jiān)聽錄音停止的事件
if (res.duration < 1000) {
api.showToast('錄音時(shí)間太短');
return;
} else {
wx.showLoading({
title: '發(fā)送中...',
});
var tempFilePath = res.tempFilePath; // 文件臨時(shí)路徑
var temp = tempFilePath.replace('.mp3', '') //轉(zhuǎn)換格式 默認(rèn)silk后綴
wx.uploadFile({
url: '*****', //上傳服務(wù)器的地址
filePath: tempFilePath, //臨時(shí)路徑
name: 'file',
header: {
contentType: "multipart/form-data", //按需求增加
},
formData: null,
success: function (res) {
wx.hideLoading();
},
fail:function(err){
wx.hideLoading();
console.log(err.errMsg);//上傳失敗
}
});
}
});
},
4.獲取上傳成功后音頻數(shù)據(jù)進(jìn)行播放,暫停。/需全局 創(chuàng)建內(nèi)部 audio
上下文 [InnerAudioContext
],參考文檔
(https://developers.weixin.qq.com/miniprogram/dev/api/InnerAudioContext.html)
const recorderManager = wx.getRecorderManager();
//播放 或是暫停語(yǔ)音
playAudio: function (e) {
// 因全局已經(jīng) 注冊(cè)過(guò)上下文 直接用innerAudioContext就可以
// 在wxml中 需要傳 data-item="{{item}}" 循環(huán)出來(lái)的當(dāng)前信息
let item = e.currentTarget.dataset.item;
//音頻地址
innerAudioContext.src = item.AudioSrc;
//在ios下靜音時(shí)播放沒(méi)有聲音,默認(rèn)為true,改為false就好了。
innerAudioContext.obeyMuteSwitch = false;
if (item.isPlay === false) {
//點(diǎn)擊播放
innerAudioContext.play();
} else {
//點(diǎn)擊暫停
innerAudioContext.stop();
};
// //播放結(jié)束
innerAudioContext.onEnded(() => {
innerAudioContext.stop();
});
},
以上就是上傳,播放,暫停功能。還有很多細(xì)節(jié),就要根據(jù)自己的需求來(lái)改寫了。希望可以幫助到你們,也歡迎大家前來(lái)指點(diǎn)!