[01天]HTML5 Audio音频频谱实现
心法 01 天
DEMO在线地址: http://demo.ccued.com/HTML5_Audio_Spectrum/
完整的示例代码。代码不多,把音乐地址换一下,自己跑跑看吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Audio Spectrum</title>
<style>
.screen{
height: 200px;
width: 400px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
background-color: #000;
}
</style>
</head>
<body>
<div class="screen"></div>
<button onclick="play()">播放</button>
<script>
class AudioSpectrum{
// 显示频谱的DOM容器
constructor(screenDom) {
this.screenDom = screenDom
this.interval = 0
this.initRect()
this.initContext()
}
// 初始化画布
initRect() {
const { width, height } = this.screenDom.getBoundingClientRect()
this.width = width
this.height = height
this.canvas = document.createElement('canvas')
this.canvas.width = width
this.canvas.height = height
this.screenDom.appendChild(this.canvas)
this.ctx = this.canvas.getContext('2d')
this.ctx.fillStyle = '#00ff00'
}
// 初始化音频分析器
initContext() {
this.context = new AudioContext()
this.analyser = this.context.createAnalyser()
this.analyser.fftSize = 1024
this.source = this.context.createBufferSource()
this.source.connect(this.analyser)
this.analyser.connect(this.context.destination)
}
// 播放HTTP音乐
playHttpAudio(src) {
if (this.source.buffer) {
this.source.stop(0)
this.initContext()
}
const request = new XMLHttpRequest()
request.open('GET', src, true)
request.responseType = 'arraybuffer'
request.onload = () => {
const data = request.response
this.context.decodeAudioData(data, buffer => {
this.source.buffer = buffer
this.source.loop = true
this.source.start(0)
this.animate()
})
}
request.send()
}
// 画频谱
render() {
const length = this.analyser.frequencyBinCount*44100 / this.context.sampleRate|0
const arrBuffer = new Uint8Array(length)
this.analyser.getByteFrequencyData(arrBuffer)
const BAR_WIDTH = 10
const BAR_SPACE = 2
const BAR_COUNT = Math.floor((this.width + BAR_SPACE) / (BAR_WIDTH + BAR_SPACE))
this.ctx.clearRect(0, 0, this.width, this.height)
for(let i = 0; i < BAR_COUNT; i++) {
const index = Math.floor(arrBuffer.length / BAR_COUNT * i)
const barHeight = arrBuffer[index] / 255 * this.height
this.ctx.beginPath()
this.ctx.rect(i * (BAR_WIDTH + BAR_SPACE), this.height - barHeight, BAR_WIDTH, barHeight)
this.ctx.closePath()
this.ctx.fill()
}
}
animate() {
this.render()
this.interval = requestAnimationFrame(() => {
this.animate()
})
}
stop() {
this.source.stop(0)
cancelAnimationFrame(this.interval)
}
}
const AS = new AudioSpectrum(document.querySelector('.screen'))
function play() {
AS.playHttpAudio('./dgzc.mp3')
}
</script>
</body>
</html>
2022-05-17 16:33:17
670
0
参与讨论