使用动态创建的dom元素和我似乎无法通过的变量创建软件合成器

时间:2013-01-11 23:33:39

标签: javascript dom web-audio

这是一个JSfiddle。 http://jsfiddle.net/ZttnJ/5/

问题是我只需要一个范围内的变量可以访问另一个范围,但如果我将变量放在更高的范围内,它就会破坏元素的动态创建。这似乎是动态创建的一个重复出现的问题dom元素和我很好奇,如果有一个锅炉板方式来解决这个问题,而无需将代码重新构建到带有原型或其他东西的构造函数中。为清楚起见,我对代码进行了评论。只有一条评论。

var SynthCreationModule = (function(){


context = new webkitAudioContext(); 
var orangeButton;
var applicationArea = document.getElementById("applicationArea"),
orangeButton = document.getElementById("orangeButton"),         
counterSynth = 1;
counterSynthMuteButton = 1;
counterSynthParameters = 1;
counterPitchInput = 1;
orangeButton.addEventListener("click",createSynth, false);     



function createSynth () {
    var pitchInput = document.createElement('input').value; // I need this to be accessible to the function called synth.onmousedown
    pitchInput.type = "range";
    pitchInput.className  = "pitchInputClass";
    pitchInput.id = "pitchInput" + (counterPitchInput++);   
    var synth = document.createElement("div"); 
    synth.className  = "synth";                        
    synth.id = "synth" + (counterSynth++);
    var synthMute = document.createElement("div");
    synthMute.className  = "synthMute";   
    synthMute.id = "synthMute" + (counterSynthMuteButton++);
    applicationArea.appendChild(synth);
    synth.appendChild(synthMute);
    synth.appendChild(pitchInput);
    $(synth).draggable({ snap: true });
    $(synth).draggable({ grid: [ 20,20 ]});



    synth.onmousedown= function () {
    oscillator = context.createOscillator(), 
    oscillator.type = 2;  
    oscillator.frequency.value = pitchInput;                   
    oscillator.connect(context.destination);  
    oscillator.noteOn(0); 


    };

    synth.onmouseup = function ()    {  
    oscillator.disconnect(); 

    };

1 个答案:

答案 0 :(得分:0)

答案是修改上面的代码:

function createSynth () {

    var pitchInput = document.createElement('input');
    pitchInput.type = "range";
    pitchInput.className  = "pitchInputClass";
    pitchInput.id = "pitchInput" + (counterPitchInput++);  
    var synth = document.createElement("div"); 
    synth.className  = "synth";                          
    synth.id = "synth" + (counterSynth++);

    var synthMute = document.createElement("div");
    synthMute.className  = "synthMute";   
    synthMute.id = "synthMute" + (counterSynthMuteButton++);
    applicationArea.appendChild(synth);
    synth.appendChild(synthMute);
    synth.appendChild(pitchInput);
    $(synth).draggable({ snap: true });
    $(synth).draggable({ grid: [ 20,20 ]});


  synth.addEventListener("mousedown",playSynth, false);

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


};