一、思路来源
最近在制作自己的博客,想在博客上写一个vue的音乐组件,正好最近看到了音频可视化的相关文章,就来试着自己做一个玩一玩。
二、WebContext的使用
初始化函数 initAudio
// 创建并返回一个webContext对象
const ac = new window.AudioContext()
// 创建一个analyser对象,用于音频时间和频率数据,以及实现数据可视化。
this.analyser = ac.createAnalyser()
// 执行傅里叶变换,用来获取频域数据(不太懂,数学不太好)。
this.analyser.fftSize = 512
this.bufferLength = this.analyser.fftSize / 2
获取audio节点
const audio = this.$refs.audio
// 创建一个MediaElementAudioSourceNode对象,输入HTML对象,即可被播放或者修改
this.source = ac.createMediaElementSource(audio)
// audio与analyser连接
this.source.connect(this.analyser)
// analyser与destination连接,返回音频最终节点,一般是扬声器
this.analyser.connect(ac.destination)
this.bufferLength = this.analyser.frequencyBinCount
三、Canvas的使用
初始化画布函数 initCanvas
// 获取画布节点
this.canvas = this.$refs.canvas
// 设置画布宽高
this.canvas.width = this.canvas.clientWidth
this.canvas.height = this.canvas.clientHeight
// 建立一个2d二维渲染上下文
this.ctx = this.canvas.getContext('2d')
四、绘制画布
渲染函数 renderBar
// Uint8Array表示一个8位无符号整型数组
this.dataArray = new Uint8Array(this.bufferLength)
// 将当前频率复制到Uint8Array数组中,最终获得音频对象。
this.analyser.getByteFrequencyData(this.dataArray)
// 清除画布
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
// 设置音柱宽度
const barWidth = this.canvas.width / this.bufferLength * 2.3
// 遍历dataArray数组获得每一项作为音柱高度,颜色自定义
this.dataArray.forEach((item, index) => {
const barHeight = item
const r = 50
const g = 250 * (index / this.bufferLength)
const b = barHeight + 25 * (index / this.bufferLength)
// 设置音柱颜色
this.ctx.fillStyle = `rgba(${r}, ${g}, ${b}, .7)`
// 设置音柱位置(x, y, width, height)
this.ctx.fillRect(barWidth * (index + 1), this.canvas.height - barHeight, barWidth, barHeight)
})
// 使用requestAnimationFrame不断渲染动画
requestAnimationFrame(this.renderCanavs)
五、效果图
加入了audio的控件和背景图美化组件。
最后
GitHub地址:github.com/hzw201718/a…