最近呢,用小程序做了一款音频播放器,自我感觉还阔以,接下来呢,给大家分享一下,大家先来看看效果图哦~
这里呢,我选择的是 wx.createInnerAudioContext 这个方法,大家可以结合文档来看这篇文章哦~
wxml
{{startTime}}
{{endTime}}
js: 1、初始化状态
data() {
url: '',
duration: '',
myAudio: '',
startTime: '00:00',
endTime: '00:00',
isplay: false,
processLen: 0,
isMovingSlider: false,
},
onReady(){
this.data.myAudio = wx.createInnerAudioContext();
this.data.myAudio.src = this.data.url;
wx.setInnerAudioOption({
obeyMuteSwitch: false
})
this.data.endTime = setTimes(this.data.duration);
this.data.myAudio.seek(0);
this.setData({
isplay: false,
startTime: '00:00',
endTime: this.data.endTime,
processLen: 0,
})
}
js: 2、点击播放、暂停、以及播放的进度
this.data.isplay = !this.data.isplay;
if(this.data.isplay) {
this.data.myAudio.play();
setTimeout(() => {
this.data.myAudio.paused;
}, 200)
} else {
this.data.myAudio.pause();
}
this.setData({
isplay: this.data.isplay
})
// 播放中...
this.data.myAudio.onTimeUpdate(() => {
if(!this.data.isMovingSlider) {
let per = (this.data.myAudio.currentTime this.data.myAudio.duration) * 100;
this.setData({
startTime: setTimes(this.data.myAudio.currentTime),
processLen: per
})
}
})
// 播放结束
this.data.myAudio.onEnded(() => {
this.setData({
isplay: false,
startTime: "00:00",
processLen: 0
})
})
// 播放出错
this.data.myAudio.onError((err) => {
console.log('audio error => ', err)
})
js: 3、进度条的拖拽
sliderChange(e) {
let long = (e.detail.value * this.data.duration) / 100;
this.data.myAudio.seek(long);
this.data.myAudio.pause();
setTimeout(() => {
this.data.myAudio.play();
})
}, 500)
this.setData({
isplay: true,
startTime: setTimes(long)
})
}
// 解决onTimeUpdate事件触发slider控件更新”和“手动拖动触发slider更新”冲突的问题
handleSliderMoveStart() {
this.setData({
isMovingSlider: true
});
},
handleSliderMoveEnd() {
this.setData({
isMovingSlider: false
});
}
js: 4、销毁音频实例
onUnload() {
this.data.myAudio.destory()
}
wxss
.audios {
display: flex;
align-items: center;
height: 88rpx;
padding: 0 40rpx;
margin: 0 auto;
box-sizing: border-box;
background:rgba(255,255,255,1);
box-shadow: 2rpx 2rpx 12rpx 0rpx rgba(199,199,204,0.6);
border-radius: 20rpx;
}
.audios .play_pause_btn {
width: 40rpx;
height: 44rpx;
margin-right: 40rpx;
}
.play_pause_btn .btn{
width: 100%;
height: 100%;
}
.audios .play_process {
flex: 1;
display: flex;
justify-content: space-between;
align-items: center;
}
代码中所用到的setTimes方法
const setTimes = (value) => {
let theTime = parseInt(value);//秒
let theTime1 = 0;//分
if(theTime > 60){
theTime1 = parseInt(theTime / 60);
theTime = parseInt(theTime % 60);
if(theTime1 > 60) {
theTime1 = parseInt(theTime1 % 60);
}
}
let theTime_y = parseInt(theTime);
if(theTime_y < 10) {
theTime_y = '0' + theTime_y
}
let results = "" + theTime_y;
if(theTime1 > 0 || theTime1 == 0) {
let theTime1_y = parseInt(theTime1);
if(theTime1_y < 10){
theTime1_y = '0' + theTime1_y;
}
results = "" + theTime1_y + ":" + results;
}
return results;
}
嗯~,到这就写的差不多了,希望能够帮助大家,如若有地方不正确,还希望在评论区多多指出,或者私信小编哦,三克油