2015-12-16 42 views
2

我正在使用audioContext實現一個簡單的鋼琴。該票據在很短的時間按正常播放,但是當一個鍵被按下持續了很長時間,然後在播放聲音infinately.please幫助謝謝使用audioContext時,音符在長按鍵上無限播放javascript

function Main() { 
    // Create audio (context) container 
    var audioCtx = new (AudioContext || webkitAudioContext)(); 
    var pressed; 
    var osc; 
    var key; 
    // Table of notes with correspending keyboard codes. Frequencies are in hertz. 
    var notesByKeyCode = { 
     65: { noteName: 'c4', frequency: 261.6, keyName: 'a' }, 
     83: { noteName: 'd4', frequency: 293.7, keyName: 's' }, 
     68: { noteName: 'e4', frequency: 329.6, keyName: 'd' }, 
     70: { noteName: 'f4', frequency: 349.2, keyName: 'f' }, 
     71: { noteName: 'g4', frequency: 392, keyName: 'g' }, 
     72: { noteName: 'a4', frequency: 440, keyName: 'h' }, 
     74: { noteName: 'b4', frequency: 493.9, keyName: 'j' }, 
     75: { noteName: 'c5', frequency: 523.3, keyName: 'k' }, 
     76: { noteName: 'd5', frequency: 587.3, keyName: 'l' }, 
     186: { noteName: 'e5', frequency: 659.3, keyName: ';' } 
    }; 



    function Key(noteName, keyName, frequency) { 
      console.log(frequency); 
      var keySound = new Sound(frequency); 
      return keySound; 
     } 

     function Sound(frequency) { 
      osc = audioCtx.createOscillator(); // Create oscillator node 
      pressed = false; // flag to indicate if sound is playing 
      osc.frequency.value = frequency; 
      osc.type = 'triangle'; 
      osc.start(0); 
     }; 

     Sound.prototype.play = function() { 
      if(!pressed) { 
       pressed = true; 
       osc.connect(audioCtx.destination); 
       console.log('play'); 
      } 
     }; 

     Sound.prototype.stop = function() { 
      osc.disconnect(); 
      pressed = false; 

      console.log('stop'); 

     }; 


     var playNote = function(event) { 
      var keyCode = event.keyCode; 
      key = new Sound(notesByKeyCode[keyCode].frequency); 
      console.log(notesByKeyCode[keyCode].frequency); 
      key.play(); 
     }; 

     var endNote = function(event) { 
      console.log(pressed,'endnote'); 
      var keyCode = event.keyCode; 
      key.stop(); 
     }; 

     window.addEventListener('keydown', playNote); 
     window.addEventListener('keyup', endNote); 

    } 

    Main(); 
+0

請發表相關的代碼。 –

+0

你到目前爲止嘗試過什麼? Stackoverflow不適用於代碼片段的訂單。告訴我們你已經嘗試過了。 – ThiagoPXP

+0

您是否正在生成音調或正在播放聲音文件? – epascarello

回答

0

如果您仍然有興趣在回答中。我想我可以嘗試解釋這種行爲。

如果您在playNote函數中調用「console.log」,您將看到如果按住該鍵多次執行該函數。我不知道爲什麼endNote函數不會停止聲音(也許「鍵」不會刪除以前的「聲音」參考)。

作爲一個快速的解決方案,我修改了代碼:

var playNote = function(event) { 
    console.log("Function xD") 
    if(!pressed) { 
     var keyCode = event.keyCode; 
     key = new Sound(notesByKeyCode[keyCode].frequency); 
     console.log(notesByKeyCode[keyCode].frequency); 
     key.play(); 
    } 
}; 

由於函數「playNote」叫了很多次,我只是複製您的條件「Sound.prototype.play」這樣就可以避免重建變量「鍵」。

這項工作至少在鉻47中。