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

音频可视化

相关推荐
行者全栈架构师18 分钟前
Spring Boot 接入 MaxKey 单点登录:6 个内部系统,一次登录全通行
java·vue.js·后端
万敏28 分钟前
Vue3 全栈实战第九周:Node.js + Express 后端从零搭建实战记录
vue.js·node.js·全栈
LEE41 分钟前
前端转型全栈 01:数据建模,前端最大的盲区
前端·javascript·后端
雪芽蓝域zzs1 小时前
第四十七节:驾驶舱大屏 ECharts 图表集成
前端·javascript·vue.js
梦醒沉醉2 小时前
7、表达日期和时间(前朝遗老Date)
javascript
白雾茫茫丶2 小时前
Vibecoding 一个主题切换动画库:13 种揭幕方式
前端·vue.js·react.js
AI码农小姐姐2 小时前
AI漫剧推文短视频动态镜头实现:FFmpeg zoompan 与 Ken Burns 效果实践
人工智能·音视频·ai工具·ai漫剧
技灵AI2 小时前
ChatGPT Images 2.5 深度解读:延迟减半、Sketch 草图与 Flare/Sunburst 双模型 API
人工智能·gpt·aigc·音视频·images2.5
雪芽蓝域zzs3 小时前
第四十九节:TagsView 右键菜单(带三角箭头)给每个 tag 增加**鼠标右键菜单**(右键标签弹出:关闭、关闭其他、关闭全部)
前端·javascript·vue.js
林澈在路上3 小时前
游戏场景背景音乐定制AI软件哪款好 2026对比推荐
大数据·人工智能·aigc·音视频