Created
July 2, 2013 21:24
-
-
Save SirPepe/5913286 to your computer and use it in GitHub Desktop.
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> | |
<meta charset="utf-8"> | |
<title>Audiospektrum</title> | |
<p> | |
<canvas width="512" height="256" style="border: 1px solid #000" id="Spektrum"></canvas> | |
</p> | |
<p> | |
<audio src="../../audio.mp3" id="Test" controls loop></audio> | |
<br> | |
<select id="AudioFn"> | |
<option value="getByteFrequencyData">getByteFrequencyData</option> | |
<option value="getByteTimeDomainData">getByteTimeDomainData</option> | |
</select> | |
</p> | |
<script> | |
(function(){ | |
// Relevante HTML-Elemente | |
var audioEl = document.getElementById('Test'); | |
var canvasEl = document.getElementById('Spektrum'); | |
var audioFnEl = document.getElementById('AudioFn'); | |
// Audio-API | |
var AudioContext = window.AudioContext || window.webkitAudioContext; | |
var context = new AudioContext(); | |
// Canvas-Zeichenfunktion | |
var draw = (function(){ | |
var context = canvasEl.getContext('2d'); | |
return function draw(signal){ | |
context.clearRect(0, 0, context.canvas.width, context.canvas.height); | |
context.beginPath(); | |
context.moveTo(0, 256 - signal[1]); | |
for(var i = 1; i < signal.length; i++){ | |
context.lineTo(i, 256 - signal[i]); | |
} | |
context.stroke(); | |
}; | |
})(); | |
// Wenn Sound abgespielt wird... | |
audioEl.addEventListener('play', function(){ | |
// Pipeline aufbauen | |
var source = context.createMediaElementSource(audioEl); | |
var analyzer = context.createAnalyser(); | |
canvasEl.width = analyzer.frequencyBinCount; | |
source.connect(analyzer); | |
source.connect(context.destination); | |
// Das Array enthält zu jedem Zeitpunkt das aktuelle Signal | |
var signal = new Uint8Array(analyzer.frequencyBinCount); | |
// Rendering loop | |
window.requestAnimationFrame(function render(){ | |
analyzer[audioFnEl.value](signal) // Signal abfragen | |
draw(signal); | |
if(!audioEl.paused){ | |
window.requestAnimationFrame(render); | |
} | |
}); | |
}, false); | |
})(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment