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

音频可视化

相关推荐
tabzzz3 分钟前
大道至简:万字漫谈前端性能监控
前端·javascript·性能优化
Irene199114 分钟前
Vue 3 项目创建方式对比(npm create vue@latest -- --typescript --eslint --prettier 自带格式化)
vue.js
用户479492835691541 分钟前
面试官问 React Fiber,这一篇文章就够了
前端·javascript·react.js
用户841794814561 小时前
vxe-table 实现滚动加载数据,无限加载数据教程
vue.js
vfvfb1 小时前
根据srt去掉无人声的地方 视频保留对白 视频去掉没有说话的段
音视频·根据srt去掉无人声的地方·视频保留对白·视频去掉对白间隙
一水鉴天1 小时前
整体设计 定稿 之23+ dashboard.html 增加三层次动态记录体系仪表盘 之2 程序 (Q199 之2) (codebuddy)
开发语言·前端·javascript
_请输入用户名1 小时前
Vue 3 源码项目结构详解
前端·vue.js
前端无涯1 小时前
Vue3---(2)setup
vue.js
前端无涯1 小时前
Vue---scoped,deep,CSS Modules
vue.js
掘金挖土1 小时前
手摸手快速搭建 Vue3 + ElementPlus 后台管理系统模板,使用 JavaScript
前端·javascript