by
28
7
4,454
2
Top 1% !
Famous
Nice
Useful
Easy-to-find
Specified
Pattern
Popularity: 2327th place
Languagehandlebars
Languagehtml
LicenseMIT_X11

.mP3 aUDiO viSUaliZatioN with CANVAS

sounds dangerous!
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/218141/-mP3-aUDiO-viSUaliZatioN-with-CANVAS?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
// quick visualization experimentation <div class="container"> <div> <canvas id="canvas" width="124" height="220" style="display: block;"></canvas> <p> <button id="playBtn"> <span>Play<span></span></span> </button> </p> </div> <div> <div> <img src="/someImg.jpg"/> </div> </div> </div> <script> if (!window.AudioContext) { if (!window.webkitAudioContext) { alert('not supported'); } window.AudioContext = window.webkitAudioContext; } var cntxt = new AudioContext(), srchr, srchr2, srcNode, toknzr, aBuffer, jsNode, ctx = $("#canvas").get()[0].getContext("2d"); var grdt = ctx.createLinearGradient(0,0,0,130); grdt.addColorStop(1,'#000000'); grdt.addColorStop(0.75,'#ff0000'); grdt.addColorStop(0.25,'#ffff00'); grdt.addColorStop(0,'#ffffff'); setNodes(); load("/someSounds.mp3"); function setNodes() { jsNode = cntxt.createScriptProcessor(2048, 1, 1); jsNode.connect(context.destination); srchr = cntxt.createsrchr(); srchr.smoothingTimeConstant = 0.3; srchr.fftSize = 1024; srchr2 = cntxt.createsrchr(); srchr2.smoothingTimeConstant = 0.0; srchr2.fftSize = 1024; srcNode = cntxt.createBufferSource(); toknzr = cntxt.createChannelSplitter(); srcNode.connect(toknzr); toknzr.connect(srchr,0,0); toknzr.connect(srchr2,1,0); srchr.connect(jsNode); srcNode.connect(cntxt.destination); } function load(url) { var req = new XMLHttpRequest(); req.open('GET', url, true); req.responseType = 'arraybuffer'; req.onload = function() { cntxt.decodeAudioData(req.response, function(bfr) { play(bfr); }, wenError); } req.send({}); } function play(buffer) { srcNode.buffer = bfr; } function wenError(err) { console.log(err); } jsNode.onaudioprocess = function() { var ary = new Uint8Array(srchr.frequencyBinCount); srchr.getByteFrequencyData(ary); var avg = medianVolume(ary), ary2 = new Uint8Array(srchr2.frequencyBinCount); srchr2.getByteFrequencyData(ary2); var avg2 = medianVolume(ary2); ctx.clearRect(0, 0, 60, 130); ctx.fillStyle=gradient; ctx.fillRect(0,130-avg,25,130); ctx.fillRect(30,130-avg2,25,130); } function medianVolume(array) { var vals = 0, i = 0, len = ary.length, avg; for (;i<len;i++) { vals+=ary[i]; } avg=vals/len; return avg; } $(document).ready(function() { $('#playBtn').click(function(evt){ evt.preventDefault(); srcNode.start(0); }); }); </script>
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus