我正在努力使JavaScript合成器可以通过键盘按键播放。我已经编写了用于检测按下的键并检测释放的键的代码,因此音调发生器的播放停止,但由于某种原因我只能播放一次。然后,在停止播放(释放后)后,它不会再次播放。目前唯一可用的键盘键是A. https://jsfiddle.net/linushg111/z062nnn1/7/
document.onkeydown = checkKey;
document.onkeyup = stops;
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var oscillator = audioCtx.createOscillator();
oscillator.type = 'sign';
// create Oscillator node
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '65') {
/*C4*//*A*/
oscillator.frequency.value = 650; // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.start(1);
}
else if (e.keyCode == '87') {
/*C#4*//*W*/
alert("test")
}
else if (e.keyCode == '83') {
/*D4*//*S*/
}
else if (e.keyCode == '69') {
/*D#4*//*E*/
}
}
function stops(){
oscillator.disconnect(audioCtx.destination);
oscillator.stop();
}