Skip to content

Instantly share code, notes, and snippets.

@b-ma
Created November 11, 2015 20:30
Show Gist options
  • Save b-ma/70694a0ad7af4cad8434 to your computer and use it in GitHub Desktop.
Save b-ma/70694a0ad7af4cad8434 to your computer and use it in GitHub Desktop.
have fun with buffer
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<button>play/pause</button>
<script>
var audioCtx = new AudioContext();
var sampleRate = audioCtx.sampleRate;
var length = sampleRate;
var audioBuffer = audioCtx.createBuffer(1, length, sampleRate);
var buffer = audioBuffer.getChannelData(0);
console.time('populateBuffer');
for (var i = 0; i < length; i++) {
var value = Math.random() * 2 - 1;
value = value * value * value * value;
// scale
buffer[i] = value * 0.03;
}
// beat
for (var i = 0; i < 20; i++) {
buffer[i] = 1;
}
// third
var step = length / 3;
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 4; j++) {
buffer[step * i + j] = 0.85;
}
}
var step = length / 4;
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
buffer[step * i + j] = 0.5;
}
}
var step = length / 5;
for (var i = 0; i < 5; i++) {
for (var j = 0; j < 7; j++) {
buffer[step * i + j] = j % 2 ? 0.8 : 0.4;
}
}
var step = length / 10;
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
buffer[step * i + j] = j % 2 ? 0.4 : -0.2;
}
}
console.timeEnd('populateBuffer');
var source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.loop = true;
var gain = audioCtx.createGain();
source.connect(gain);
gain.connect(audioCtx.destination);
source.start(audioCtx.currentTime);
var state = 'playing';
document.querySelector('button').addEventListener('click', function() {
if (state === 'playing') {
gain.gain.value = 0;
state = 'paused';
} else {
gain.gain.value = 1;
state = 'playing';
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment