123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- /* 隐藏原生 video 控件,用 Canvas 展示动画 */
- #audioPlayer { display: none; }
- body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #000; }
- </style>
- </head>
- <body>
- <input type="button" onclick="audio.play()" value="播放" />
- <input type="button" onclick="audio.pause()" value="暂停" />
- <canvas id="wrap" height="550" width="800"></canvas>
- <script>
- var wrap = document.getElementById("wrap");
- var cxt = wrap.getContext("2d");
- //获取API
- var AudioContext = AudioContext || webkitAudioContext;
- var context = new AudioContext;
- //加载媒体
- var audio = new Audio("http://192.168.3.36:5002/play/5e25571cae884d307e0a8f576fbc8632?t=1743822135234");
- //创建节点
- var source = context.createMediaElementSource(audio);
- var analyser = context.createAnalyser();
- //连接:source → analyser → destination
- source.connect(analyser);
- analyser.connect(context.destination);
- //创建数据
- var output = new Uint8Array(361);
- //计算出采样频率44100所需的缓冲区长度
- var length = analyser.frequencyBinCount * 44100 / context.sampleRate | 0;
- //创建数据
- var output2 = new Uint8Array(length);
- (function drawSpectrum() {
- analyser.getByteFrequencyData(output);//获取频域数据
- cxt.clearRect(0, 0, wrap.width, wrap.height);
- //画线条
- for (var i = 0; i < output.length; i++) {
- var value = output[i] / 10;
- //绘制左半边
- cxt.beginPath();
- cxt.lineWidth = 1;
- cxt.moveTo(300, 300);
- cxt.lineTo(Math.cos((i * 0.5 + 90) / 180 * Math.PI) * (200 + value) + 300, (- Math.sin((i * 0.5 + 90) / 180 * Math.PI) * (200 + value) + 300));
- cxt.stroke();
- //绘制右半边
- cxt.beginPath();
- cxt.lineWidth = 1;
- cxt.moveTo(300, 300);
- cxt.lineTo((Math.sin((i * 0.5) / 180 * Math.PI) * (200 + value) + 300), -Math.cos((i * 0.5) / 180 * Math.PI) * (200 + value) + 300);
- cxt.stroke();
- }
- //画一个小圆,将线条覆盖
- cxt.beginPath();
- cxt.lineWidth = 1;
- cxt.arc(300, 300, 200, 0, 2 * Math.PI, false);
- cxt.fillStyle = "#fff";
- cxt.stroke();
- cxt.fill();
- //将缓冲区的数据绘制到Canvas上
- analyser.getByteTimeDomainData(output2);
- var height = 100, width = 400;
- cxt.beginPath();
- for (var i = 0; i < width; i++) {
- cxt.lineTo(i + 100, 300 - (height / 2 * (output2[output2.length * i / width | 0] / 256 - 0.5)));
- }
- cxt.stroke();
- //请求下一帧
- requestAnimationFrame(drawSpectrum);
- })();
- </script>
- </body>
- </html>
|