Skip to content

Instantly share code, notes, and snippets.

@koron
Created March 15, 2014 14:56
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 koron/9568553 to your computer and use it in GitHub Desktop.
Save koron/9568553 to your computer and use it in GitHub Desktop.
Web Auido APIで矩形波
<!doctype html>
<body onload="load();">
<button onclick="play();">Play</button>
<button onclick="stop();">Stop</button>
<script>
var Player = function() {
if (window.webkitAudioContext) {
this.context = new webkitAudioContext();
} else {
this.context = new AudioContext();
}
this.node = this.context.createScriptProcessor(16384, 0, 1);
this.count = 0;
this.pos = 0;
var Z = this;
var freq = 440;
this.node.onaudioprocess = function(e) {
var data = e.outputBuffer.getChannelData(0);
//var k = freq * 2 * Math.PI / Z.context.sampleRate;
var k = Z.context.sampleRate / (freq * 2);
for (var i = 0; i < 16384; ++i) {
data[i] = ((Math.floor(Z.pos / k) % 2) * 2 - 1) * .2;
++Z.pos;
}
};
}
Player.prototype.play = function() {
this.pos = 0;
this.node.connect(this.context.destination);
}
Player.prototype.stop = function() {
this.node.disconnect();
}
var player;
function load() {
player = new Player();
}
function play() {
player.play();
}
function stop() {
player.stop();
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment