Html可视化频谱
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML5音频可视化频谱跳动代码</title>
<style>
* {
margin: 0;
padding: 0;
}
#canvas {
display: block;
background: linear-gradient(135deg, rgb(62, 95, 42) 0%, rgb(230, 132, 110) 100%);
}
</style>
</head>
<body>
<audio id="myaudio" autoplay="autoplay" src="./bgm1.mp3"></audio>
<!-- <video id="myaudio" width="800" height="350" autoplay="autoplay" loop="loop" controls="controls" src="http://cnzb24.com/home/first"></video> -->
<!-- <audio id="myaudio" autoplay="autoplay" preload="auto" loop controls="controls" src="bgm1.mp3"> </audio> -->
<canvas id="canvas"></canvas>
<script>
window.onload = function () {
var oAudio = document.getElementById('myaudio');
window.onclick = function () {
if (oAudio.paused) {
oAudio.play();
} else {
oAudio.pause();
}
}
var oCtx = new AudioContext();
var audioSrc = oCtx.createMediaElementSource(oAudio);
var analyser = oCtx.createAnalyser();
audioSrc.connect(analyser);
analyser.connect(oCtx.destination);
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var oW = canvas.width;
var oH = canvas.height;
var color1 = ctx.createLinearGradient(oW / 2, oH / 2 - 30, oW / 2, oH / 2 - 100);
var color2 = ctx.createLinearGradient(oW / 2, oH / 2 + 30, oW / 2, oH / 2 + 100);
color1.addColorStop(0, '#000');
color1.addColorStop(.5, '#069');
color1.addColorStop(1, '#3b6abf');
color2.addColorStop(0, '#000');
color2.addColorStop(.5, '#069');
color2.addColorStop(1, '#265f04');
var count = 150;
var voiceHeight = new Uint8Array(analyser.frequencyBinCount);
function draw() {
analyser.getByteFrequencyData(voiceHeight);
var step = Math.round(voiceHeight.length / count);
ctx.clearRect(0, 0, oW, oH);
for (var i = 0; i < count; i++) {
var audioHeight = voiceHeight[step * i];
ctx.fillStyle = color1;
ctx.fillRect(oW / 2 + (i * 10), oH / 2, 7, -audioHeight);
ctx.fillRect(oW / 2 - (i * 10), oH / 2, 7, -audioHeight);
ctx.fillStyle = color2;
ctx.fillRect(oW / 2 + (i * 10), oH / 2, 7, audioHeight);
ctx.fillRect(oW / 2 - (i * 10), oH / 2, 7, audioHeight);
}
window.requestAnimationFrame(draw);
}
draw();
}
</script>
</body>
</html>