使用音訊效果

通過連結源節點和目標節點之間的節點,可以將效果應用於音訊。在這個例子中,我們使用增益節點來靜音源,並且只在特定時間發出聲音。這允許我們建立摩爾斯電碼。

function morse(gainNode, pattern) {
  let silenceTimeout = 300;
  let noiseTimeout;
  
  if(pattern === '') {
    //We are done here
    return;
  } else if(pattern.charAt(0) === '.') {
    noiseTimeout = 100;
  } else if(pattern.charAt(0) === '-') {
    noiseTimeout = 400;
  } else {
    console.error(pattern.charAt(0), ': Character not recognized.');
    return;
  }
  
  //Briefly let sound through this gain node
  gainNode.gain.value = 1;
  window.setTimeout(function() {
    gainNode.gain.value = 0;
    window.setTimeout(morse, silenceTimeout, gainNode, pattern.substring(1));
  }, noiseTimeout);
}
let audioContext = new (window.AudioContext || window.webkitAudioContext)();

let sourceNode = audioContext.createOscillator();
let gainNode = audioContext.createGain();

sourceNode.type = 'sine';
sourceNode.frequency.value = 261.6;
sourceNode.detune.value = 0;

//Mute sound going through this gain node
gainNode.gain.value = 0;

//SourceNode -> GainNode -> Speakers
sourceNode.connect(gainNode);
gainNode.connect(audioContext.destination);

//The source node starts outputting
sourceNode.start();

//Output SOS
morse(gainNode, '...---...');