音频可视化工具的多个实例

时间:2016-07-26 19:16:12

标签: javascript audio

这是我在Stack Overflow上的第一篇文章,但我以前曾多次使用过这个网站作为资源。

我通过观看教程学到了一些代码,它的工作非常棒。该代码可以显示传递文件所具有的任何音频频率。然而,当我试图制作音频可视化器的第二个实例时,它不能很好地完成,这是我所期望的。问题是我无法弄清楚如何将代码从单次使用转换为多次使用文件。

如果需要更多信息,请告诉我,我会提供。我想我需要以某种方式改变事件监听器,但我对如何失去了。

以下是我用来制作可视化工具的JavaScript:

//create a new instance of an audio object and adjust some of its properties
var audio = new Audio();
audio.src = "audio_file_goes_here.mp3";
audio.controls = true;
audio.loop = true;
audio.autoplay = false;
audio.crossOrigin = "anonymous";

// establish all the variables that the analyser will use
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;

// initilize the MP3 player after the pages loads all of the HTML into the window
window.addEventListener("load", initMp3Player, false);

function initMp3Player(){
  document.getElementById('audio_box').appendChild(audio);
  context = new AudioContext();
  analyser = context.createAnalyser();
  canvas = document.getElementById('analyser_render');
  ctx = canvas.getContext('2d');
  source = context.createMediaElementSource(audio);
  source.connect(analyser);
  analyser.connect(context.destination);
  frameLooper();
}

//frameLooper animates nay style of graphics at 60fps based on browser
function frameLooper(){
  window.requestAnimationFrame(frameLooper);
  fbc_array = new Uint8Array(analyser.frequencyBinCount);
  analyser.getByteFrequencyData(fbc_array);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#00CCFF";
  bars=100;
  for (var i = 0; i < bars; i++){
    bar_x = i * 3;
    bar_width = 2;
    bar_height = -(fbc_array[i] / 2);
    ctx.fillRect (bar_x, canvas.height, bar_width, bar_height);
  }
}

以下是与

对应的HTML细分
<div id="mp3_player">
                <div id="audio_box"> </div>
                <canvas id="analyser_render"> </div> 

这是CSS

div#mp3_player{
  width:510px; 
  height:70px; 
  background: #000;       
  padding:5px;
  margin:50px auto;
}
div#mp3_player > div > audio{
  width:500px; 
  background: #000;
  float:left;
}

div#mp3_player > canvas {
  width:500px;
  height:30px; 
  background:#002d3c;
  float:left;
}

0 个答案:

没有答案