如何改变滑块的鼠标上下触发振荡器的音调,并在使用Javascript和Web音频API的鼠标up事件后保留状态

How to change pitch of mousedown/up triggered oscillator with slider and have it retain state after mouseup event with Javascript and Web Audio API

本文关键字:鼠标 Web Javascript 音频 保留 状态 事件 API up 改变 何改变      更新时间:2023-09-26

代码中的注释应该是自解释的。

<div id="pad2"></div>
<input id="oscPitch" type="range" min="5" max="500" step="1" value="50"/>
<p>Pitch</p>
<script>

context = new webkitAudioContext();         
var pad2 = document.getElementById("pad2");
pad2.onmousedown= function () {
oscillator = context.createOscillator(),  // Creates the oscillator 
oscillator.type = 2;                      // 4 oscillator types    // Pitch
oscillator.connect(context.destination);  // Connects it to output
oscillator.noteOn(0); 
document.getElementById('oscPitch').addEventListener('change', function() {
oscillator.frequency.value = this.value;
});  
};
// If you remove the mouse up event below and change the pitch slider it works fine. But I want to have the pitch slider retain it's state before & after the mouse up event. Itried storing the getElementId of the slider element to a variable and playing with it but I couldn't chisel it out.
pad2.onmouseup = function ()    {  
oscillator.disconnect(); 
};


</script>

编辑。我更接近于这个:

<input id="oscPitch" type="range" min="5" max="500" step="1" value="90"/>
<p>Pitch</p>
<script>

context = new webkitAudioContext();         
var pad2 = document.getElementById("pad2");
var pitchState = document.getElementById('oscPitch').value;
pad2.onmousedown= function () {
oscillator = context.createOscillator(),  // Creates the oscillator 
oscillator.type = 2;  
oscillator.frequency.value = pitchState;                   
oscillator.connect(context.destination);  // Connects it to output
oscillator.noteOn(0); 

};
pad2.onmouseup = function ()    {  
oscillator.disconnect(); 
};
</script>

明白了。

<input id="oscPitch" type="range" min="5" max="500" step="1" value="90"/>
<p>Pitch</p>
<script>

context = new webkitAudioContext();         
var pad2 = document.getElementById("pad2");

pad2.onmousedown= function () {
var pitchState = document.getElementById('oscPitch').value;
oscillator = context.createOscillator(),  // Creates the oscillator 
oscillator.type = 2;  
oscillator.frequency.value = pitchState;                   
oscillator.connect(context.destination);  // Connects it to output
oscillator.noteOn(0); 

};
pad2.onmouseup = function ()    {  
oscillator.disconnect(); 
};





</script>