Skip to content

Instantly share code, notes, and snippets.

@kioku-systemk
Created April 5, 2014 19:32
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 kioku-systemk/9996943 to your computer and use it in GitHub Desktop.
Save kioku-systemk/9996943 to your computer and use it in GitHub Desktop.
Generate Wave sample
<p><script>(function(){
/*
Generate Wave sample
*/
var time = 1.0, // 1[sec]
sampling = 44100, // Samples per second
chan = 2,
waveLen = time * sampling * chan;
function genWave(buf)
{
var hz = 440,//[hz]
PI2 = 3.141592*2,
vol = 10000,
L = 0, R = 0, wl = waveLen;
for (var i = 0; i < wl; ++i){
L = R = Math.floor(vol*Math.sin(i*hz*PI2/44100.0));
buf[2*i ] = L;
buf[2*i+1] = R;
}
}
function createAudio()
{
var i, wave, l1, l2, y,
wlen = waveLen,
wbuf = new Int32Array(wlen);
genWave(wbuf);
// Create wave header
var sizeInt = 4;
l1 = wlen * sizeInt - 8,
l2 = l1 - 36;
wave = String.fromCharCode(
82,73,70,70,
l1 & 255,(l1 >> 8) & 255,(l1 >> 16) & 255,l1 >> 24,
87,65,86,69,102,109,116,32,16,0,0,0,1,0,2,0,
68,172,0,0,16,177,2,0,4,0,16,0,100,97,116,97,
l2 & 255,(l2 >> 8) & 255,(l2 >> 16) & 255,l2 >> 24
);
for (var i = 0; i < wlen; i++){
y = wbuf[i];
y = y < -32767 ? -32767 : (y > 32767 ? 32767 : y); // clipping
wave += String.fromCharCode(y & 255, (y >> 8) & 255);
}
return new Audio("data:audio/wav;base64," + btoa(wave));
};
var audio = createAudio();
audio.play();
// disp time
var d = document.createElement("div");
document.body.appendChild(d);
setInterval(function(){
d.innerHTML = "Time="+audio.currentTime;
},16);
})()</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment