トップへ(mam-mam.net/)

JavascriptでPCのキーボード入力で音階を鳴らす ~AudioContext,oscillator

検索:

キーボードを押すと音が鳴ります

「キーボード入力を開始」ボタンを押し、パソコンのキーボードのキーを押すと音が鳴ります。

音量:
5


キーボード入力を開始
キーボード操作
「Z」キー
【ド】
「X」キー
【レ】
「C」キー
【ミ】
「V」キー
【ファ】
「B」キー
【ソ】
「N」キー
【ラ】
「M」キー
【シ】
「,」キー
【ド】

同時に複数のキーを押すと和音を鳴らすこともできます。

ソースコード


<div style="display:flex;"><div>音量:</div><div id="vol_label">5</div></div>
<input type="range" value="5" max="100" min="1" step="1" id="vol" style="max-width:100%;width:600px;"><br>
<br>
<a style="cursor:pointer;" class="bt102 play_start">キーボード入力を開始</a><br>

<script>
  var audioCtx=null,oscillator=null;
  var gainNode=null,vol=5;//音量関連
  var ms=[
    {"name":"ド"  ,"hz":261,"os":null,"active":false,"key":90},
    {"name":"レ"  ,"hz":294,"os":null,"active":false,"key":88},
    {"name":"ミ"  ,"hz":330,"os":null,"active":false,"key":67},
    {"name":"ファ","hz":349,"os":null,"active":false,"key":86},
    {"name":"ソ"  ,"hz":392,"os":null,"active":false,"key":66},
    {"name":"ラ"  ,"hz":440,"os":null,"active":false,"key":78},
    {"name":"シ"  ,"hz":494,"os":null,"active":false,"key":77},
    {"name":"ド"  ,"hz":522,"os":null,"active":false,"key":188},
  ];
  window.addEventListener('DOMContentLoaded',function(){
    document.getElementById('vol').setAttribute('disabled','');
    document.querySelector(".play_start").addEventListener('click',function(){
      audioCtx = new (window.AudioContext || window.webkitAudioContext)();
      gainNode = audioCtx.createGain();
      gainNode.gain.value=vol/100;
      document.getElementById('vol').removeAttribute('disabled','');

      //音量変更
      document.getElementById('vol').addEventListener('input',function(){
        document.getElementById('vol_label').innerHTML=document.getElementById('vol').value;
        vol=document.getElementById('vol').value;
        if(gainNode!=null){
          gainNode.gain.value=vol/100;
        }
      });
      document.addEventListener('keydown',function(){
        for(let i=0;i<ms.length;i++){
          if(ms[i].key==event.keyCode && ms[i].active==false){
            ms[i].os=audioCtx.createOscillator();
            ms[i].os.type="sine";//sine,square,sawtooth,triangle
            ms[i].os.connect(gainNode).connect(audioCtx.destination);
            //周波数設定
            ms[i].os.frequency.setValueAtTime(ms[i].hz, audioCtx.currentTime);
            ms[i].os.start();
            ms[i].active=true;
            break;
          }
        }
      });
      document.addEventListener('keyup',function(){
        for(let i=0;i<ms.length;i++){
          if(ms[i].key==event.keyCode){
            ms[i].os.stop();
            ms[i].active=false;
            break;
          }
        }
      });
    });
  });
</script>