2017-02-11 6 views
0

Я знаю, что это звучит легко или очевидно, но я не могу сделать эту работу.Как создать функцию для создания осцилляторов с помощью Web Audio Api

Смотрите этот фрагмент:

ctx = new AudioContext(); 
 
gain = ctx.createGain(); 
 
gain.connect(ctx.destination); 
 
gain.gain.value = 0.5; 
 

 

 
osc1 = ctx.createOscillator(); 
 
osc1.connect(gain); 
 
osc1.frequency.value = 450; 
 
osc1.start(); 
 
osc1.stop(2); 
 

 
osc2 = ctx.createOscillator(); 
 
osc2.connect(gain); 
 
osc2.frequency.value = 500; 
 
osc2.start(); 
 
osc2.stop(2); 
 
console.log("playing");

Он играет два Осцилляторы в то время без проблем, но он повторяет код. Если я попытаюсь поместить избыточный код в функцию, он не сработает.

ctx = new AudioContext(); 
 
gain = ctx.createGain(); 
 
createAndPlayOsc(450); 
 
createAndPlayOsc(500); 
 

 

 
function createAndPlayOsc(freq){ 
 
    console.log("creating osc with freq " + freq); 
 
    var osc = ctx.createOscillator(); 
 
    osc.connect(gain); 
 
    osc.frequency.value = freq; 
 
    osc.start(); 
 
    osc.stop(2); 
 
    console.log("playing osc with freq " + freq); 
 
}

Даже если я посылаю AudioContext

ctx = new AudioContext(); 
 
gain = ctx.createGain(); 
 
createAndPlayOsc(450, ctx); 
 
createAndPlayOsc(500, ctx); 
 

 

 
function createAndPlayOsc(freq, context){ 
 
    console.log("creating osc with freq " + freq); 
 
    var osc = context.createOscillator(); 
 
    osc.connect(gain); 
 
    osc.frequency.value = freq; 
 
    osc.start(); 
 
    osc.stop(2); 
 
    console.log("playing osc with freq " + freq); 
 
}

или оба gainNode и контекст

ctx = new AudioContext(); 
 
gain = ctx.createGain(); 
 
createAndPlayOsc(450, ctx, gain); 
 
createAndPlayOsc(500, ctx, gain); 
 

 

 
function createAndPlayOsc(freq, context, gainNode){ 
 
    console.log("creating osc with freq " + freq); 
 
    var osc = context.createOscillator(); 
 
    osc.connect(gainNode); 
 
    osc.frequency.value = freq; 
 
    osc.start(); 
 
    osc.stop(2); 
 
    console.log("playing osc with freq " + freq); 
 
}

Что мне не хватает?

ответ

1

Вы забыли подключить усиление к контексту:

gain.connect(ctx.destination); 
+0

Ой ... Так легко ... Спасибо. У меня возникают проблемы с классом провайдера в приложении Ionic2, который просто воспроизводит «Oscs», если они созданы в конструкторе, но не в методе, и я полагаю, я просто хотел, чтобы это было связано с этим вопросом :( – distante

Смежные вопросы