tmp.html 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. /* 隐藏原生 video 控件,用 Canvas 展示动画 */
  6. #audioPlayer { display: none; }
  7. body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #000; }
  8. </style>
  9. </head>
  10. <body>
  11. <input type="button" onclick="audio.play()" value="播放" />
  12. <input type="button" onclick="audio.pause()" value="暂停" />
  13. <canvas id="wrap" height="550" width="800"></canvas>
  14. <script>
  15. var wrap = document.getElementById("wrap");
  16. var cxt = wrap.getContext("2d");
  17. //获取API
  18. var AudioContext = AudioContext || webkitAudioContext;
  19. var context = new AudioContext;
  20. //加载媒体
  21. var audio = new Audio("http://192.168.3.36:5002/play/5e25571cae884d307e0a8f576fbc8632?t=1743822135234");
  22. //创建节点
  23. var source = context.createMediaElementSource(audio);
  24. var analyser = context.createAnalyser();
  25. //连接:source → analyser → destination
  26. source.connect(analyser);
  27. analyser.connect(context.destination);
  28. //创建数据
  29. var output = new Uint8Array(361);
  30. //计算出采样频率44100所需的缓冲区长度
  31. var length = analyser.frequencyBinCount * 44100 / context.sampleRate | 0;
  32. //创建数据
  33. var output2 = new Uint8Array(length);
  34. (function drawSpectrum() {
  35. analyser.getByteFrequencyData(output);//获取频域数据
  36. cxt.clearRect(0, 0, wrap.width, wrap.height);
  37. //画线条
  38. for (var i = 0; i < output.length; i++) {
  39. var value = output[i] / 10;
  40. //绘制左半边
  41. cxt.beginPath();
  42. cxt.lineWidth = 1;
  43. cxt.moveTo(300, 300);
  44. 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));
  45. cxt.stroke();
  46. //绘制右半边
  47. cxt.beginPath();
  48. cxt.lineWidth = 1;
  49. cxt.moveTo(300, 300);
  50. cxt.lineTo((Math.sin((i * 0.5) / 180 * Math.PI) * (200 + value) + 300), -Math.cos((i * 0.5) / 180 * Math.PI) * (200 + value) + 300);
  51. cxt.stroke();
  52. }
  53. //画一个小圆,将线条覆盖
  54. cxt.beginPath();
  55. cxt.lineWidth = 1;
  56. cxt.arc(300, 300, 200, 0, 2 * Math.PI, false);
  57. cxt.fillStyle = "#fff";
  58. cxt.stroke();
  59. cxt.fill();
  60. //将缓冲区的数据绘制到Canvas上
  61. analyser.getByteTimeDomainData(output2);
  62. var height = 100, width = 400;
  63. cxt.beginPath();
  64. for (var i = 0; i < width; i++) {
  65. cxt.lineTo(i + 100, 300 - (height / 2 * (output2[output2.length * i / width | 0] / 256 - 0.5)));
  66. }
  67. cxt.stroke();
  68. //请求下一帧
  69. requestAnimationFrame(drawSpectrum);
  70. })();
  71. </script>
  72. </body>
  73. </html>