[英]Toggle One And Off - JavaScript - Web Audio API
我是音頻工程師,剛開始使用JavaScript和HTML5,尤其是WEB音頻API。
我有連接到目標(輸出)的振盪器代碼。 這是代碼
我想要一個按鈕來連接和斷開振盪器到我設法使其啟動但無法斷開的目的地。
<html>
<head>
<script>
//creating the context
context = new webkitAudioContext(); //allways the first code for audio API
function osc1(frequency){ // Creating a function that has an oscillator going to gainNode and then going to the destination
//creating AudioNodes and AudioParams
//creating OscillatorNode
var oscillator = context.createOscillator(); //creating Node's as Variables
oscillator.type = 0; //0 is a sine wave
oscillator.noteOn(0); // turning on the oscillator
oscillator.frequency.value = frequency;// telling that frequency in () of the function equals to what
//creating GainNode
var gain = context.createGainNode(); // creating the Gain node
gain.gain.value = 1; // setting up the value for gain node
//Making the connections
oscillator.connect(gain); // connecting oscillator to gain
gain.connect(context.destination); // connecting gain to destination (speakers)
}; // now we have a function called osc1(we can put frequency in here) then we can re call
</script>
</head>
<body>
<input type="button" value="on" onClick="osc1(500);" />
</body>
</html>
我知道斷開連接的代碼是oscillator.disconnect();
,但我不知道如何執行它。
也許您想在函數外部聲明振盪器變量:
var context = new webkitAudioContext();
var oscillator = context.createOscillator();
function osc1(frequency){
var button = document.getElementsByTagName('input')[0];
if (button.value === 'off') {
button.value = 'on';
oscillator.disconnect();
} else {
button.value = 'off';
// same as your original code (connect, noteOn...)
我也在做這個。
您執行oscillator.disconnect(0),其中零表示輸出編號。
我認為這意味着,如果將振盪器分別連接到增益節點和濾波器節點,則增益將為disconnect(0),而濾波器將為disconnect(1)。
我認為跟蹤輸出是我們的工作,因為這看起來不是內置的。
我希望規范能夠有所變化,以便我們可以將我們想要斷開的實際節點傳遞給connect()。
前面已經提到過,但是您需要公開oscillator
變量(可能在全局范圍內),以便您的off函數可以斷開它的連接(確保您未在onclick
處理程序中重新聲明oscillator
變量)。
這是一個工作示例: http : //jsbin.com/iwetiy/1/edit
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.