技术就餐

导航

音频可视化

<template>
<div>
<canvas ref="row" style="background: #000;width:100%;height: 400px;"></canvas>
<audio ref="audio" controls src="../../static/flow.mp3" @play="play"></audio>
</div>
</template>
<script>
export default{
data(){
return{
isInit:false,
dataArr:null,
analy:null
}
},
 
mounted(){
 
},
methods:{
play(e){
if(this.isInit) return
const audCtx = new (window.AudioContext || window.webkitAudioContext)();
const source = audCtx.createMediaElementSource(this.$refs.audio)
this.analy = audCtx.createAnalyser()
this.analy.fftSize = 512
this.dataArr = new Uint8Array(this.analy.frequencyBinCount)
source.connect(this.analy)
this.analy.connect(audCtx.destination)
this.isInit = true
this.draw()
},
draw(){
requestAnimationFrame(this.draw)
const canvas = this.$refs.row
let _this = this
if (!canvas) {
return
}
const { width, height } = canvas.getBoundingClientRect()
const dpi = 2
canvas.width = width * dpi
canvas.height = height * dpi
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
let { width: w, height: h } = canvas
w /= dpi
h /= dpi
const ctx = canvas.getContext('2d')
ctx.scale(dpi, dpi)
ctx.clearRect(0, 0, w, h)
this.analy.getByteFrequencyData(this.dataArr)
const len = this.dataArr.length
const barwidth = w / len
ctx.fillStyle = '#78c5f7';
for(let i =0;i < len ;i++){
const data = this.dataArr[i]
const barh = (data / 255) * h
const x = i * barwidth
const y = h - barh
ctx.fillRect(x,y,barwidth - 2,barh)
}
}
}
}
</script>
<style lang="scss" scoped>
</style>

posted on 2023-06-12 11:55  技术就餐  阅读(8)  评论(0编辑  收藏  举报