I have made a function to produce a drum sound how ever after being called 4 times it stops working with the error:
TypeError: null is not an object (evaluating 'audioCtx.sampleRate') Showing in the console.
What's wrong with this function? My code is:
drum = function(){
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var frameCount = audioCtx.sampleRate/20
var myArrayBuffer = audioCtx.createBuffer(1, frameCount, audioCtx.sampleRate);
var nowBuffering = myArrayBuffer.getChannelData(0);
for (var i = 0; i < frameCount; i++) {
nowBuffering[i] =Math.sin(i**(1/1.8)/4)
}
var source = audioCtx.createBufferSource();
source.buffer = myArrayBuffer; source.connect(audioCtx.destination);
source.start();
}
Your audioCtx
assignment should be moved outside of drum()
, as it will get called every time, eventually throwing an exception since you can't create more than 6 audio contexts in a document.