我正在使用audioContext实现一架简单的钢琴。音符在短时间内正常播放,但当长时间连续按下某个键时,声音就会自然播放。请帮助,谢谢
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();
如果您仍然对答案感兴趣。我想我可以试着解释一下这种行为。
如果您在playNote函数中调用"console.log",您将看到该函数在按住键的情况下执行多次。我不知道为什么endNote函数没有停止声音(也许"key"没有删除之前对"sound"的引用)。
作为一个快速解决方案,我修改了代码:
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.protype.play"中复制您的条件,以避免重新创建变量"key"。
这至少在Chrome 47中有效。