Created
July 14, 2013 13:25
-
-
Save arisetyo/5994270 to your computer and use it in GitHub Desktop.
Spectrum Analyzer Using webkitAudioContext
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 name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <meta name="author" content="Galenic"> | |
| <title>Spectrum</title> | |
| </head> | |
| <body> | |
| <canvas id="songcanvas" width="640" height="320px"></canvas> | |
| <script type="text/javascript"> | |
| var context = new webkitAudioContext(); | |
| var audioAnimation; | |
| var audioBuffer; | |
| var sourceNode; | |
| var analyser; | |
| var audio; | |
| // get the context from the canvas to draw on | |
| var canvas = document.getElementById('songcanvas'); | |
| var ctx = canvas.getContext("2d"); | |
| var gradient = ctx.createLinearGradient(0,0,0,canvas.height); | |
| gradient.addColorStop(1,'#550000'); | |
| gradient.addColorStop(0.75,'#ff0000'); | |
| gradient.addColorStop(0.25,'#ffff00'); | |
| gradient.addColorStop(0,'#ffff00'); | |
| ctx.fillStyle = gradient; | |
| function loadSong(url) { | |
| if (audio) audio.remove(); | |
| if (sourceNode) sourceNode.disconnect(); | |
| cancelAnimationFrame(audioAnimation); | |
| audio = new Audio(); | |
| audio.src = url; | |
| audio.addEventListener("canplay", function(e) { | |
| setupAudioNodes(); | |
| }, false); | |
| } | |
| function setupAudioNodes() { | |
| analyser = (analyser || context.createAnalyser()); | |
| analyser.smoothingTimeConstant = 0.8; | |
| analyser.fftSize = 512; | |
| sourceNode = context.createMediaElementSource(audio); | |
| sourceNode.connect(analyser); | |
| sourceNode.connect(context.destination); | |
| audio.play(); | |
| drawSpectrum(); | |
| } | |
| function drawSpectrum() { | |
| var WIDTH = canvas.width, | |
| HEIGHT= canvas.height, | |
| array = new Uint8Array(analyser.frequencyBinCount); | |
| analyser.getByteFrequencyData(array); | |
| ctx.clearRect(0, 0, WIDTH, HEIGHT); | |
| audioAnimation = requestAnimationFrame(drawSpectrum); | |
| for ( var i = 0; i < (array.length); i++ ){ | |
| var value = array[i]; | |
| ctx.fillRect(i*5,HEIGHT-value,3,HEIGHT); | |
| } | |
| } | |
| loadSong("mp3/the_wind.mp3"); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment