Web Audio APIで任意の周波数の正弦波を鳴らす(HTML/Javascript)
HTML5のWeb Audio APIを使って任意の周波数で正弦波を鳴らす電子音叉的なものを作ってみる。
目次
HTML5のサウンド処理
HTML5ではこんな風にAudioタグを使って簡単に音を出す事が出来る。
<audio src="<オーディオファイル" contorols></audio>
Audioタグは簡単に使える反面、エフェクト等の音声処理の機能は無い。そのようなシーンにはWeb Audio APIを使えば良いようだ。
参考
・Web Audio API – Web API インターフェイス | MDN
・HTML5 の Web Audio API で音楽してみる | CYOKODOG
このあたりを参考にしつつ作成してみた。
完成品
周波数: Hz音量:
ソースコード
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(function() {
var ctx;
var oscillator;
var gainNode;
$("#play").click(function() {
if (!ctx) {
ctx = new AudioContext();
} else if (ctx.state === "suspended") {
ctx.resume();
}
if (oscillator) {
oscillator.stop();
}
oscillator = ctx.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.value = document.getElementById('freq').value;
gainNode = ctx.createGain();
gainNode.gain.value = document.getElementById('vol').value;
oscillator.connect(gainNode);
gainNode.connect(ctx.destination);
oscillator.start();
});
$("#stop").click(function() {
if (oscillator) {
oscillator.stop();
}
});
$("#vol").change(function(e) {
if (gainNode) {
gainNode.gain.value = this.value;
}
});
$("#freq").change(function(e) {
if (oscillator) {
oscillator.frequency.value = this.value;
}
});
});
</script>
</head>
<body>
周波数: <input id="freq" type="number" style="width:50px" min="20" max="20000" value="440" step="1" required>Hz
<br>
音量: <input id="vol" type="range" min="0" max="1" step="0.01" value="0.5">
<br>
<button id="play">play</button>
<button id="stop">stop</button>
</body>
</html>
近い内、レイアウトやアイコンのデザインを改良してメトロノームとかも合わせて作りたい。
コメント