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.效果

音频可视化

相关推荐
VOOHU_201815 分钟前
VOOHU沃虎:音频变压器的主要作用是什么?什么情况下必须使用?
网络·物联网·音视频·电子元器件
ZC跨境爬虫1 小时前
UI前端美化技能提升日志day7:(原生苹方字体全局适配+合规页脚完整像素级落地)
前端·javascript·ui·html·交互
好运的阿财1 小时前
OpenClaw工具拆解之tts+web_search
前端·javascript·python·ai·ai编程·openclaw·openclaw工具
APIshop1 小时前
小红书笔记视频详情接口深度解析:smallredbook.item_get_video_pro
数据库·笔记·音视频
whinc1 小时前
Node.js技术周刊 2026年第17周
前端·javascript
nbsaas-boot1 小时前
100万门店级分货系统架构设计
前端·javascript·vue.js
l1t2 小时前
DeepSeek v4辅助生成的单文件SQL查询示例页面
javascript·数据库·sql
笋笋~3 小时前
el-tree 拖拽事件隔离:实现句柄独立控制,区域分离
javascript·vue.js·elementui
前端那点事3 小时前
Vue生命周期速查:Vue2+Vue3钩子全解析,新手也能秒懂
前端·vue.js
AI服务老曹3 小时前
【架构深评】深度解析异构计算下的 AI 视频管理平台:从 GB28181 接入到 X86/ARM 容器化部署的全链路实战
人工智能·架构·音视频