vue-music关于Player播放器组件详解

2020-06-16 05:55:56易采站长站整理

进度条

audio元素监听 timeupdate 事件获取当前播放时间的 可读写属性 时间戳。用formt做格式化时间处理,(_pad 为补零函数 )

获取音频总时长 currentSong.duration


<div class="progress-wrapper">
<span class="time time-l">{{ format(currentTime) }}</span>
<div class="progress-bar-wrapper">
<progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar>
</div>
<span class="time time-r">{{ format(currentSong.duration) }}</span>
</div>

<audio :src="currentSong.url" ref="audio" @canplay="ready" @error="error" @timeupdate="updateTime" @ended="end"></audio>


updateTime(e){
this.currentTime = e.target.currentTime; // 获取当前播放时间段
},

format(interval){
interval = interval | 0;
const minute = interval/60 | 0;
const second = this._pad(interval % 60);
return `${minute}:${second}`;
},

_pad(num,n=2){
let len = num.toString().length;
while(len<n){
num = '0' + num;
len ++;
}
return num;
},

建立progress-bar 组件 接收pencent 进度参数,设置进度条宽度和小球的位置。player组件 设置计算属性percent


percent(){
return this.currentTime / this.currentSong.duration  // 当前时长除以总时长
},

progress-bar 组件


<div class="progress-bar" ref="progressBar" @click="progressClick">
<div class="bar-inner">
<div class="progress" ref="progress"></div>
<div class="progress-btn-wrapper" ref="progressBtn"
@touchstart.prevent="progressTouchStart"
@touchmove.prevent="progressTouchMove"
@touchend="progressTouchEnd"
>
<div class="progress-btn"></div>
</div>
</div>
</div>


const progressBtnWidth = 16 //小球宽度

props:{
percent:{
type:Number,
default:0
}
},

watch:{
percent(newPercent){
if(newPercent>=0 && !this.touch.initated){    
const barWidth = this.$refs.progressBar.clientWidth - progressBtnWidth;
const offsetWidth = newPercent * barWidth;
this.$refs.progress.style.width = `${offsetWidth}px`;
this.$refs.progressBtn.style.transform=`translate3d(${offsetWidth}px,0,0)`
}
}
}

设置拖动

在进度条小按钮progressBtn 上添加touchstart,touchmove,touchend 事件监听方法,事件添加 prevent 防止拖动默认浏览器行为,获取拖动的信息进行计算