Last active
August 29, 2015 14:09
-
-
Save DonKarlssonSan/43977057f514714d826b to your computer and use it in GitHub Desktop.
Analyze the frequency of the sound from the microphone
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> | |
<title>Frequency Analyser - Web Audio API Demo</title> | |
</head> | |
<body> | |
<canvas id="theCanvas" width="1024" height="256"></canvas> <br/> | |
<button id="startButton" type="button">Start</button> | |
<script> | |
(function() { | |
var AudioContext = window.AudioContext || window.webkitAudioContext; | |
var mediaStreamSource; | |
var analyser; | |
var canvas = document.querySelector('#theCanvas'); | |
var canvasContext = canvas.getContext("2d"); | |
var dataArray; | |
canvasWidth = canvas.width; | |
canvasHeight = canvas.height; | |
navigator.getUserMedia = (navigator.getUserMedia || | |
navigator.webkitGetUserMedia || | |
navigator.mozGetUserMedia || | |
navigator.msGetUserMedia); | |
if (navigator.getUserMedia) { | |
var audioContext = new AudioContext(); | |
document.querySelector("#startButton").addEventListener('click', startButton_Clicked); | |
function gotStream(stream) { | |
var audioContext = new AudioContext(); | |
mediaStreamSource = audioContext.createMediaStreamSource(stream); | |
analyser = audioContext.createAnalyser(); | |
mediaStreamSource.connect(analyser); | |
startDrawing(); | |
} | |
function startButton_Clicked() { | |
this.disabled = true; | |
navigator.getUserMedia( {audio:true}, gotStream, error); | |
} | |
function startDrawing() { | |
analyser.fftSize = 2048; | |
var bufferLength = analyser.frequencyBinCount; | |
console.log(bufferLength); | |
dataArray = new Uint8Array(bufferLength); | |
function drawAgain() { | |
canvasContext.clearRect(0, 0, canvasWidth, canvasWidth); | |
requestAnimationFrame(drawAgain); | |
analyser.getByteFrequencyData(dataArray); | |
for(var i = 0; i < bufferLength; i++){ | |
canvasContext.beginPath(); | |
canvasContext.moveTo(i, 255); | |
canvasContext.lineTo(i, 255 - dataArray[i]); | |
canvasContext.closePath(); | |
canvasContext.stroke(); | |
} | |
} | |
drawAgain(); | |
} | |
function error(message) { | |
console.log(message); | |
} | |
} else { | |
document.querySelector("#startButton").disabled = true; | |
alert("Sorry, you can't use the mic in this web browser. Try the latest version of Firefox, Chrome or Opera."); | |
} | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment