js音乐可视化

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js音频可视化</title>
<style>
      #file {
   
          position: fixed;
          top: 10px;
          left: 10px;
          z-index: 100;
      }
      
      #canvas {
   
          position: fixed;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
      }
      
      #audio {
   
          position: fixed;
          left: 10px;
          bottom: 10px;
          width: calc(100% - 20px);
      }
</style>
</head>
<body>
 <h2 style&
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的使用 JavaScript 可视化音乐的案例: ```html <!DOCTYPE html> <html> <head> <title>音乐可视化</title> <style> canvas { background-color: #000; } </style> </head> <body> <audio id="audio" controls> <source src="music.mp3" type="audio/mpeg"> </audio> <canvas id="canvas"></canvas> <script> // 获取 canvas 元素 var canvas = document.getElementById("canvas"); // 设置 canvas 的宽和高 canvas.width = window.innerWidth; canvas.height = window.innerHeight; // 获取 canvas 的上下文 var ctx = canvas.getContext("2d"); // 获取音频元素 var audio = document.getElementById("audio"); // 创建音频上下文 var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // 创建音频源节点 var source = audioCtx.createMediaElementSource(audio); // 创建分析器节点 var analyser = audioCtx.createAnalyser(); // 连接节点 source.connect(analyser); analyser.connect(audioCtx.destination); // 设置分析器的参数 analyser.fftSize = 2048; var bufferLength = analyser.frequencyBinCount; var dataArray = new Uint8Array(bufferLength); // 绘制可视化效果 function draw() { // 清空画布 ctx.clearRect(0, 0, canvas.width, canvas.height); // 获取音频数据 analyser.getByteFrequencyData(dataArray); // 设置绘制样式 ctx.fillStyle = "#fff"; ctx.lineWidth = 2; ctx.strokeStyle = "#fff"; ctx.beginPath(); var sliceWidth = canvas.width * 1.0 / bufferLength; var x = 0; for (var i = 0; i < bufferLength; i++) { var v = dataArray[i] / 128.0; var y = v * canvas.height / 2; if (i === 0) { ctx.moveTo(x, y); } else { ctx.lineTo(x, y); } x += sliceWidth; } ctx.lineTo(canvas.width, canvas.height / 2); ctx.stroke(); requestAnimationFrame(draw); } // 开始绘制 draw(); </script> </body> </html> ``` 以上代码实现了一个简单的音乐可视化效果。用户可以在页面上播放音乐,并且通过 canvas 元素将音频数据可视化为波形图。在代码中,使用了 Web Audio API 中的 AnalyserNode 节点来获取音频数据,并且使用 canvas 绘制波形图。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值