I am trying to create a flappybird like game where the amplitude of microphone is used to fly a plane. The problem is I keep getting an "Uncaught TypeError: Cannot read property 'getByteTimeDomainData' of undefined
" when trying to access the audio signal data using analyserNode
.
I think the problem is created because initialization of the AudioContext
happens AFTER calling AnalyserNode since console log shows that getAudioAmp()
gets declared before draw()
before $(document).ready()
using console.log()
.
Here is relevant parts of the code below:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var audioContext;
var mediaStreamSource;
var analyser;
var bufferLength;
var dataArray;
var myAudio = document.querySelector('audio');
$(document).ready(function() {
navigator.getUserMedia = (navigator.webkitGetUserMedia ||navigator.mozGetUserMedia ||navigator.msGetUserMedia);
if (navigator.getUserMedia) {
navigator.getUserMedia({video: false,audio: true},
function(stream) {
if (window.AudioContext) {
audioContext = new AudioContext();
} else {
audioContext = new webkitAudioContext();
}
mediaStreamSource = audioContext.createMediaStreamSource(stream);
console.log(1)
analyser = audioContext.createAnalyser(); <----initialization of AnalyserNode------------
bufferLength = analyser.frequencyBinCount;
dataArray = new Uint8Array(bufferLength);
mediaStreamSource.connect(analyser);},
function(){alert("The following error occured: " + err.name);});
} else {
alert('OOPS No browser Support');
}
});
var getAudioAmp = function() {
console.log(2)
analyser.getByteTimeDomainData(dataArray); <---Line that causes Error----------------
var total = 0;
for (var i = 0; i < bufferLength; i++) {
total += dataArray[i];
var amp = total / dataArray.length;
}
return amp;
}
function draw() {
console.log(3)
ctx.clearRect(0, 0, canvas.width, canvas.height);
amp = getAudioAmp() <----------------where I call getAudioAmp()-------------
console.log(amp)
drawScore()
drawStat()
drawplane()
drawBricks()
collisionDetection()
score++;
requestAnimationFrame(draw);
}
draw();
here is the code in jsfiddle https://fiddle.jshell.net/kkawabat/bh4dbo1y/44/