Skip to content

Instantly share code, notes, and snippets.

@zakuroishikuro
Created April 21, 2016 21:04
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 zakuroishikuro/d2385691e15858f4348a0ed77bc0ac5d to your computer and use it in GitHub Desktop.
Save zakuroishikuro/d2385691e15858f4348a0ed77bc0ac5d to your computer and use it in GitHub Desktop.
simple html piano
<!DOCTYPE html>
<meta charset="utf-8">
<style>
button {
width: 5em;
height: 8em;
box-shadow: 0px 3px 2px gray;
text-shadow: 0px 3px 3px gray;
transition: 0.1s;
}
button:active {
transform: translateY(6px);
box-shadow: 0px 0px 0px gray;
}
</style>
<script>
var c = new AudioContext();
function play_sound(freq, duration, type){
if (freq === undefined) freq = 440;
if (duration === undefined) duration = 0.8;
if (type === undefined) type = "sine";
var g = c.createGain();
g.connect(c.destination);
var o = c.createOscillator();
o.frequency.value = freq;
o.type = type;
o.connect(g);
var now = c.currentTime;
o.start(now);
o.stop(now + duration);
g.gain.setValueAtTime(1.0, now);
g.gain.exponentialRampToValueAtTime(0.01, now + duration);
return o;
}
var COMMON_RATIO = Math.pow(2, 1/12); //1.0594630943592953...
function calc_piano_frequency(key_index, pitch){
if (key_index === undefined) key_index = 49;
if (pitch === undefined) pitch = 440;
var ratio = Math.pow(COMMON_RATIO, key_index - 49);
return pitch * ratio;
}
function push(key){
var pitch = document.getElementById("pitch_range").value;
var type = document.getElementById("type").value;
var freq = calc_piano_frequency(key, pitch);
play_sound(freq, 0.8, type);
}
</script>
<button onclick="push(52)">ド</button>
<button onclick="push(54)">レ</button>
<button onclick="push(56)">ミ</button>
<button onclick="push(57)">ファ</button>
<button onclick="push(59)">ソ</button>
<button onclick="push(61)">ラ</button>
<button onclick="push(63)">シ</button>
<button onclick="push(64)">ド</button>
<p>type:
<select id="type">
<option value="sine">正弦波(sine) ... 口笛、オルガン</option>
<option value="square">矩形波(square) ... クラリネット</option>
<option value="sawtooth">ノコギリ波(sawtooth) ... バイオリン、トランペット</option>
<option value="triangle">三角波(triangle) ... リコーダー、フルート</option>
</select>
</p>
<p>
pitch: <input id="pitch_range" type="range" min=110 max=3520 value="440" list="freq_list" oninput="document.getElementById('pitch').value = this.value">
<input type="number" id="pitch" value="440" style="width: 10em" onchange="document.getElementById('pitch_range').value = this.value">Hz
<datalist id="freq_list">
<option value="110" />
<option value="220" />
<option value="440" />
<option value="880" />
<option value="1760" />
<option value="3520" />
</datalist>
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment