Jules
Jules

Reputation: 311

Use AudioContext to display song's overall waveform

I am trying to display the waveform of a song pretty much like SoundCloud does it per individual track but I am having some difficulties.

So far this is what I am assuming to be the right start.

  $scope.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  $scope.analyser = $scope.audioCtx.createAnalyser();

  $scope.myAudio = new Audio;
  $scope.myAudio.src = "http://localhost:9000/mp3/song.mp3";

  // Create a MediaElementAudioSourceNode
  // Feed the HTMLMediaElement into it
  $scope.source = $scope.audioCtx.createMediaElementSource( $scope.myAudio );

  $scope.source.connect( $scope.analyser );

  $scope.analyser.fftSize = 64;

  $scope.bufferLength = $scope.analyser.frequencyBinCount;
  $scope.dataArray = new Uint8Array( $scope.bufferLength );
  $scope.newDataArray = new Float32Array( $scope.analyser.fftSize );

  $scope.analyser.getByteTimeDomainData( $scope.dataArray );

  $scope.canvas = document.querySelector('.visualizer');
  $scope.canvasCtx = $scope.canvas.getContext("2d");

  function draw() {

    $scope.WIDTH = $scope.canvas.width;
    $scope.HEIGHT = $scope.canvas.height;

    $scope.drawVisual = requestAnimationFrame( draw );

    $scope.analyser.getByteTimeDomainData( $scope.dataArray );

    $scope.canvasCtx.fillStyle = 'rgb(200, 200, 200)';
    $scope.canvasCtx.fillRect(0, 0, $scope.WIDTH, $scope.HEIGHT);

    $scope.canvasCtx.lineWidth = 2;
    $scope.canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
  };

  draw();

Well this is obviously only partial, but the end result would be to display the overall track with the waveform of the track clearly represented from start to finish across the width of a canvas.

Much appreciate the help with this.

Respectfully,

Jules

Upvotes: 0

Views: 439

Answers (0)

Related Questions