vue+canvas音频可视化

1.代码

复制代码
<template>
    <div class="subGuide">
        <canvas id="canvas"></canvas>
        <br>
        <audio id="audio" src="./audio.mp3" controls></audio>
    </div>
</template>

<script>
export default {
    name: 'subGuide',
    data() {
        return {
        }
    },
    mounted() {
        const audioEle = document.querySelector('audio')
        const cvs = document.querySelector('canvas')
        const ctx = cvs.getContext('2d')
        function initCvs() {
            cvs.width = (window.innerWidth / 2) * devicePixelRatio
            cvs.height = (window.innerHeight / 3) * devicePixelRatio
        }
        initCvs()

        let isInit = false
        let dateArray = null
        let analyser = null

        audioEle.addEventListener('play', function (e) {
            if (isInit) return
            const audCtx = new AudioContext()
            const source = audCtx.createMediaElementSource(audioEle)
            analyser = audCtx.createAnalyser()
            analyser.fftSize = 512
            dateArray = new Uint8Array(256)
            source.connect(analyser)
            analyser.connect(audCtx.destination)
            isInit = true
        })

        function draw() {
            requestAnimationFrame(draw)
            const { width, height } = cvs
            ctx.clearRect(0, 0, width, height)
            if (!isInit) return
            analyser.getByteFrequencyData(dateArray)
            const len = dateArray.length / 2.5
            ctx.fillStyle = '#266fff'
            const barWidth = width / len / 2
            for (let i = 0; i < len; i++) {
                const data = dateArray[i]
                const barHeight = (data / 255) * height
                const x1 = i * barWidth + width / 2
                const x2 = width / 2 - (i + 1) * barWidth
                const y = height - barHeight
                ctx.fillRect(x1, y, barWidth - 2, barHeight)
                ctx.fillRect(x2, y, barWidth - 2, barHeight)
            }
        }
        draw()
    },
    methods: {
        
    }
}
</script>

<style lang="scss" scoped></style>

2.效果

音频可视化

相关推荐
左夕4 分钟前
分不清apply,bind,call?看这篇文章就够了
前端·javascript
滕青山1 小时前
文本行过滤/筛选 在线工具核心JS实现
前端·javascript·vue.js
时光不负努力1 小时前
编程常用模式集合
前端·javascript·typescript
时光不负努力1 小时前
ts+vue3开发规范
vue.js·typescript
大雨还洅下1 小时前
前端JS: 跨域解决
javascript
OpenTiny社区1 小时前
OpenTiny NEXT-SDK 重磅发布:四步把你的前端应用变成智能应用
前端·javascript·ai编程
梦想CAD控件1 小时前
在线CAD开发包结构与功能说明
前端·javascript·vue.js
时光不负努力1 小时前
TS 常用工具类型
前端·javascript·typescript
SuperEugene2 小时前
Vue状态管理扫盲篇:Vuex 到 Pinia | 为什么大家都在迁移?核心用法对比
前端·vue.js·面试
徐小夕2 小时前
pxcharts-vue:一款专为 Vue3 打造的开源多维表格解决方案
前端·vue.js·github