Skip to content

Instantly share code, notes, and snippets.

@jgimbel
Created March 22, 2017 19:42
Show Gist options
  • Save jgimbel/4ac470f703ce7b594be1711bfa0b8b86 to your computer and use it in GitHub Desktop.
Save jgimbel/4ac470f703ce7b594be1711bfa0b8b86 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>
Audio
</title>
</head>
<body>
<audio id="myAudio" autoplay preload="auto" class="audio--source">
Your browser does not support the <code data-v-1733d37e="">audio</code> element.
<source data-v-1733d37e="" src="/07.mp3" type="audio/mp3">
</audio>
<canvas id="myCanvas" width="1200" height="300">
An alternative text describing what your canvas displays.
</canvas>
<button onclick="audioCtx.suspend()">STAHP!</button>
<button onclick="audioCtx.resume()">STAHT!</button>
<script>
var audioCtx = new window.AudioContext();
var analyser = audioCtx.createAnalyser();
var canvas = document.getElementById('myCanvas'); // in your HTML this element appears as <canvas id="mycanvas"></canvas>
var canvasCtx = canvas.getContext('2d');
var audio = document.getElementById('myAudio');
var audioSrc = audioCtx.createMediaElementSource(audio);
audioSrc.connect(analyser);
var WIDTH = canvas.offsetWidth,
HEIGHT = canvas.offsetHeight
var frequencyData = new Uint8Array(analyser.fftSize);
var bufferLength = analyser.fftSize
analyser.getByteTimeDomainData(frequencyData);
audioSrc.connect(audioCtx.destination);
// draw an oscilloscope of the current audio source
var skipFrameRate = 3
var frame = 0
function draw() {
drawVisual = requestAnimationFrame(draw);
frame++
if(frame % skipFrameRate !== 0) return
analyser.getByteTimeDomainData(frequencyData);
canvasCtx.fillStyle = 'rgb(200, 200, 200)';
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
canvasCtx.beginPath();
var sliceWidth = WIDTH * 1.0 / bufferLength;
var x = 0;
var avg = 0
var toSkip = 10
canvasCtx.fillStyle = 'rgb(0, 0, 0)';
for (var i = 0; i < bufferLength; i++) {
avg += frequencyData[i] / 128.0
if(i % toSkip !== 0) continue
var v = avg / toSkip;
// if(v > 1) v = 1 - (1 - v)
var y = v * HEIGHT / 2;
avg = 0;
canvasCtx.fillRect(x*toSkip, y, sliceWidth*(toSkip*.75), HEIGHT - y)
//canvasCtx.lineTo(x, y);
x += sliceWidth
}
//canvasCtx.lineTo(canvas.width, canvas.height / 2);
canvasCtx.stroke();
}
draw();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment