拍手で動くミラーボール

このエントリーをはてなブックマークに追加

obnizをつかって音に反応するミラーボールを作ってみました!(製作時間:1時間)

Program

<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://obniz.io/js/jquery-3.2.1.min.js"></script>
  <script src="https://unpkg.com/obniz@1.2.1/obniz.js" crossorigin="anonymous"></script>
</head>
<body>

<div id="obniz-debug"></div>
<h1>obniz instant html</h1>
<button id="on">ON</button>
<button id="off">OFF</button>
<div id="print"></div>

<script>
let audioMax = 0;
let audioSum = 0;
let audioNum= 0;
  let lastVoltage = 0;
var obniz = new Obniz("OBNIZ_ID");
  let before = "off";
obniz.onconnect = async function () {
    obniz.io9.output(true);
      obniz.io10.output(false);
      obniz.io11.output(true);
  

  obniz.display.clear();
  obniz.display.print("Let's hit a hand.");
  var microphone = obniz.wired("AE_MICAMP", {vcc:0, gnd:1, out:2});
  
  
  microphone.onchange = function(voltage){
    lastVoltage = voltage;
    if(voltage > audioMax){
      audioMax = voltage;
    }
    audioSum += voltage;
    audioNum += 1;
  }


  var usb = obniz.wired("USB" , {gnd:11, vcc:8} );
  usb.off();
  setInterval(()=>{
      console.log(audioMax + ";"+(audioSum/audioNum).toFixed(2)+";"+(audioMax - (audioSum/audioNum)).toFixed(2) );
    
    if(audioMax - (audioSum/audioNum) > 0.8){
       if(before == "off"){
        obniz.display.clear();
          obniz.display.print("Nice!!");
       }
      before = "on";
        usb.on();
    }else{
         usb.off();
      if(before == "on"){
        obniz.display.clear();
          obniz.display.print("Let's hit a hand.");
      }
      before = "off";
    }
      
    audioMax = lastVoltage;
    audioSum = lastVoltage;
    audioNum = 1;
    
  },1000);
  
  
}

</script>
</body>
</html>