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

音频可视化

相关推荐
忆源36 分钟前
【Qt】之音视频编程1:QtAV的背景和安装篇
开发语言·qt·音视频
油丶酸萝卜别吃2 小时前
OpenLayers 精确经过三个点的曲线绘制
javascript
ShallowLin2 小时前
vue3学习——组合式 API:生命周期钩子
前端·javascript·vue.js
Nejosi_念旧2 小时前
Vue API 、element-plus自动导入插件
前端·javascript·vue.js
麻芝汤圆3 小时前
MapReduce 入门实战:WordCount 程序
大数据·前端·javascript·ajax·spark·mapreduce
路溪非溪5 小时前
各种音频产品及场景总结
音视频
Peter 谭5 小时前
React Hooks 实现原理深度解析:从基础到源码级理解
前端·javascript·react.js·前端框架·ecmascript
周胡杰6 小时前
鸿蒙接入flutter环境变量配置windows-命令行或者手动配置-到项目的创建-运行demo项目
javascript·windows·flutter·华为·harmonyos·鸿蒙·鸿蒙系统
乌夷7 小时前
axios结合AbortController取消文件上传
开发语言·前端·javascript
科技小E7 小时前
WebRTC技术EasyRTC嵌入式音视频通信SDK打造远程实时视频通话监控巡检解决方案
人工智能·音视频