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();
請發表相關的代碼。 –
你到目前爲止嘗試過什麼? Stackoverflow不適用於代碼片段的訂單。告訴我們你已經嘗試過了。 – ThiagoPXP
您是否正在生成音調或正在播放聲音文件? – epascarello