Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created July 11, 2014 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mayfer/27a91eb0aed7a55b8f07 to your computer and use it in GitHub Desktop.
Save mayfer/27a91eb0aed7a55b8f07 to your computer and use it in GitHub Desktop.
Basic audio generation
// Built from Mohit Cheppudira's sine wave generator - http://0xfe.blogspot.com
// Modified by Murat Ayfer - http://muratayfer.com
soundWave = function(context) {
// xs is a list of x (time) values, one per wave.
// time is not represented as synchronized clicks or milliseconds, its passing is freq dependent
// so that's why we keep a value per each wave.
this.xs = [];
this.counter = 0;
this.context = context;
this.sampleRate = this.context.sampleRate; // 44100 by default
this.sampleRateMillisecond = this.sampleRate / 1000;
this.playing = false;
this.node = context.createJavaScriptNode(1024, 1, 2);
var that = this;
this.node.onaudioprocess = function(e) { that.process(e) };
}
soundWave.prototype.process = function(e) {
// Get a reference to the output buffer and fill it up.
var channels = [ e.outputBuffer.getChannelData(0), e.outputBuffer.getChannelData(1) ];
var buffer_size = channels[0].length;
var num_channels = channels.length;
var amplitude = 0;
for (var i = 0; i < buffer_size; i++) {
y = Math.sin((this.counter) * Math.PI * 2 * 440 / this.sampleRate);
if(amplitude = 0) {
amplitude = 1;
} else {
amplitude = 0;
}
for(var k = 0; k < num_channels; k++) {
channels[k][i] = y;
}
this.counter += 1;
}
}
soundWave.prototype.play = function() {
this.node.connect(this.context.destination);
this.playing = true;
}
soundWave.prototype.pause = function() {
this.playing = false;
}
var audio = new AudioContext();
var wave = new soundWave(audio);
wave.play();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment