Created
November 16, 2021 14:51
-
-
Save egonelbre/58cfdac56474072a54c267763376f274 to your computer and use it in GitHub Desktop.
Hooking up WebAudio Analyser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<script src="/~watch.js"></script> | |
</head> | |
<body> | |
<audio id="sourceElement" controls> | |
<source src="music.mp3" type="audio/mpeg"> | |
</audio> | |
<br> | |
<canvas id="timeElement" style="border: 1px solid #000"></canvas> | |
<br> | |
<canvas id="freqElement" style="border: 1px solid #000"></canvas> | |
<script> | |
let audioContext = new window.AudioContext(); | |
let source = audioContext.createMediaElementSource(sourceElement); | |
sourceElement.onplay = function() { | |
audioContext.resume(); | |
} | |
let analyser = audioContext.createAnalyser(); | |
source.connect(analyser); | |
analyser.connect(audioContext.destination); | |
let timeCanvas = timeElement.getContext("2d"); | |
let timeDomain = new Uint8Array(analyser.frequencyBinCount); | |
let freqCanvas = freqElement.getContext("2d"); | |
let freqDomain = new Uint8Array(analyser.frequencyBinCount); | |
setInterval(function() { | |
var w = timeElement.clientWidth; | |
var bw = Math.ceil(w / analyser.frequencyBinCount); | |
var h = timeElement.clientHeight; | |
analyser.getByteTimeDomainData(timeDomain); | |
timeCanvas.clearRect(0, 0, w, h); | |
for(var i = 0; i < analyser.frequencyBinCount; i++) { | |
var bin = timeDomain[i]; | |
timeCanvas.fillRect(i * bw, 0, bw, h * bin / 255); | |
} | |
var w = freqElement.clientWidth; | |
var bw = Math.ceil(w / analyser.frequencyBinCount); | |
var h = freqElement.clientHeight; | |
analyser.getByteFrequencyData(freqDomain); | |
freqCanvas.clearRect(0, 0, w, h); | |
for(var i = 0; i < analyser.frequencyBinCount; i++) { | |
var bin = freqDomain[i]; | |
freqCanvas.fillRect(i * bw, 0, bw, h * bin / 255); | |
} | |
}, 15) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment