Skip to content

Instantly share code, notes, and snippets.

@AnastasiaDunbar
Last active February 7, 2019 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnastasiaDunbar/f755d777acf2cfc2df99efa2918f9f61 to your computer and use it in GitHub Desktop.
Save AnastasiaDunbar/f755d777acf2cfc2df99efa2918f9f61 to your computer and use it in GitHub Desktop.
DIY and no more libraries.
function dsp(time){
var master=Math.sin(Math.PI*2*440*time)*Math.exp(-3*time);
return master;
}
var audioContext=new AudioContext(),
bufferSize=2048, //256,512,1024,2048,4096,8192,16384
node=audioContext.createScriptProcessor(bufferSize,0,2), //bufferSize,inputChannels,outputChannels
time=0;
node.onaudioprocess=event=>{
var L=event.outputBuffer.getChannelData(0),
R=event.outputBuffer.getChannelData(1),
value;
for(var i=0;i<bufferSize;i++){
value=dsp(time+(i/audioContext.sampleRate));
if(Array.isArray(value)){ //Stereo.
L[i]=value[0];R[i]=value[1];
}else{ //Mono.
L[i]=value;R[i]=value;
}
}
time+=bufferSize/audioContext.sampleRate;
};
node.connect(audioContext.destination);
@AnastasiaDunbar
Copy link
Author

AnastasiaDunbar commented Feb 7, 2019

Oh no, I shouldn't have used event.inputBuffer here where it was used for source.connect(scriptNode); in MDN's example, therefore no input channels should've been used in this snippet. source.start(); was used to play the audio file that's loaded asynchronously into source.buffer.
I now have to go through my p5.js projects because of this. But I knew already that I've done something wrong here (its mild verbosity can be seen, and uses input.length as if it were the size of the output buffer) but it just took a while for me to figure out why.

@AnastasiaDunbar
Copy link
Author

But I've fixed it now. :^)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment