录音播放组件的效果图,如下:
实现思路如下:
- 先获取录音时间的长度,渲染到页面中
- 点击播放的时候,播放音频,与此同时打开计时器,从0 开始记录时间
- 将记录的时间,动态更新到页面中,就实现了时间的增加
- 播放录音的动画,由上面的灰色透明条和下面的红色过程条组成
- 在播放录音的过程中,通过计算比例,动态增大下面红色过程条的宽度
- 在录音播放结束后,将录音条宽度恢复至初始位置,录音时间展示录音的时长
代码如下:
<div class="newAudio">
<div class="voice-container">
<div
class="play-button"
id="play-button"
:class="{ 'play-button-pause': isPlay }"
@click="play($event)"
>
<audio id="audio" ref="audio" :src="audioUrl"></audio>
</div>
<div class="progress" ref="progressGray">
<div class="progress-red-con" ref="progress-red-con">
<div class="progress-red"></div>
</div>
</div>
<div v-if="isPlay" class="count-down">{{ progressStart }}s</div>
<div v-else class="count-down">
{{ audioPalyTime > 0 ? audioPalyTime : progressStart }}s
</div>
</div>
</div>
data(){
return{
timer: '',
audioTime: '',
audioPalyTime: 0,
progressStart: 0,
isPlay: false,
}
}
mounted () {
setTimeout(() => {
const audio = this.$refs.audio
// 获取音频的dom节点
this.targetNode = this.$refs['progress-red-con']
if (audio) {
// 录音资源
audio.src = this.audioUrl
audio.load()
audio.oncanplay = () => {
// 获取录音的时间长度
this.audioPalyTime = Math.round(audio.duration)
this.audioTime = Math.round(audio.duration)
}
}
}, 500)
},
// 音乐播放器的播放
play (e) {
const media = e.currentTarget.querySelector('#audio')
if (this.isPlay) {
// 暂停
media.pause()
// 重新加载
media.load()
this.progressStart = 0
this.isPlay = false
if (this.targetNode) {
this.targetNode.style.width = 0
}
clearTimeout(this.timer)
} else {
media.play()
this.isPlay = true
this.progress()
}
},
// 播放过程
progress () {
let timeStart = 1
let audioTime = this.audioTime * 100
this.count = timeStart
// 记录时间
this.timer = setInterval(() => {
if (this.count <= audioTime) {
this.count++
this.progressStart = parseInt(this.count / 100)
// 动态改变红色div的宽度
this.targetNode.style.width = (115 / audioTime) * this.count + 'px'
} else {
this.isPlay = false
this.progressStart = 0
// 清楚定时器
clearInterval(this.timer)
this.timer = null
if (this.targetNode) {
// 恢复底部div的默认宽度
this.targetNode.style.width = 0
}
}
}, 10)
}
以上就是个人录音播放组件的实现过程,如有疑问,可评论留言。