概要
paiza.ioでelixirやってみた。
練習問題やってみた。
練習問題
ドレミを鳴らせ。
サンプルコード
IO.puts """
<!doctype html>
<html>
<head>
</head>
<body>
<textarea id="src">
"""
IO.puts "ドドソソララソソファファミミレレドドソソファファミミレレソソファファミミレレドドソソララソソファファミミレレド"
IO.puts """
</textarea>
<button onclick="run()">play</button>
<script>
var doremi = function() {
this.audioContext = new AudioContext();
}
doremi.prototype.oto = function(key) {
var osciillatorNode = this.audioContext.createOscillator();
var envelopeGen = this.audioContext.createGain();
var freq = 440.0 * Math.pow(2.0, (key - 69.0) / 12.0);
osciillatorNode.frequency.value = freq;
osciillatorNode.connect(envelopeGen);
envelopeGen.connect(this.audioContext.destination);
var t1 = this.audioContext.currentTime;
envelopeGen.gain.cancelScheduledValues(t1);
envelopeGen.gain.setValueAtTime(1, t1);
osciillatorNode.start();
var release = 0.2;
var keyUpTime = this.audioContext.currentTime;
envelopeGen.gain.setValueAtTime(envelopeGen.gain.value, keyUpTime);
envelopeGen.gain.linearRampToValueAtTime(0, keyUpTime + release);
osciillatorNode.stop(keyUpTime + release);
}
doremi.prototype.sleep = function(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++)
{
if ((new Date().getTime() - start) > 90 * milliseconds)
{
break;
}
}
}
doremi.prototype.play = function(mml) {
for (var i = 0; i < mml.length; i++)
{
mml = mml.replace('ァ', '');
}
for (var i = 0; i < mml.length; i++)
{
var a = mml[i];
switch (a)
{
case 'シ':
this.oto('71');
break;
case 'ド':
this.oto('72');
break;
case 'レ':
this.oto('74');
break;
case 'ミ':
this.oto('76');
break;
case 'フ':
this.oto('77');
break;
case 'ソ':
this.oto('79');
break;
case 'ラ':
this.oto('81');
break;
default:
break;
}
this.sleep(4);
}
}
var src = document.getElementById('src');
var doremi0 = new doremi;
function run() {
doremi0.play(src.value);
}
</script>
</body>
</html>
"""
成果物
以上。