WebAudio - Oscillator

by juberti

HTML

<button>▶</button>
<button id="bar">▶2</button>
<video id="foo" muted autoplay/>

JavaScript

window.AudioContext = window.AudioContext || window.webkitAudioContext;

var audioContext = new AudioContext();
var mss;
var foo = document.getElementById("foo");
//var dest = audioContext.creatMediaStreamDestination();
var button = document.querySelector('button');
button.addEventListener('click', playNewSound4);
var button2 = document.getElementById("bar");
button2.addEventListener('click', () => { audioContext.resume(); });

function playNewSound1() {
  var oscillator = audioContext.createOscillator();
  //oscillator.type = 'square';'square';'sawtooth', 'triangle','
  oscillator.type = 'sine';
  oscillator.frequency.value = 440; // value in hertz
  var gain = audioContext.createGain();
  oscillator.connect(gain);
  gain.connect(audioContext.destination);

  oscillator.start(0);
}

function playNewSound2() {
  var src = 'https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_1MG.mp3';
  audioContext.resume().then(load(src));
}

 function load(src) {
   console.log("load");
   console.log(audioContext.state);
  const request = new XMLHttpRequest();
  request.open("GET", src, true);
  request.responseType = "arraybuffer";
  request.onload = function() {
    var buffer;
    let undecodedAudio = request.response;
    audioContext.decodeAudioData(undecodedAudio, (data) => play(data));
  };
  request.send();
}

function play(buffer) {
  console.log("play");
  console.log(audioContext.state);
  const source = audioContext.createBufferSource();
  source.buffer = buffer;
  source.connect(audioContext.destination);
  source.start(0);
}

function playNewSound3() {
  var audioContext2 = new AudioContext();
  var oscillator = audioContext2.createOscillator();
  //oscillator.type = 'square';'square';'sawtooth', 'triangle','
  oscillator.type = 'sine';
  oscillator.frequency.value = 440; // value in hertz
  var gain = audioContext2.createGain();
  oscillator.connect(gain);
  
  var dest = audioContext2.createMediaStreamDestination();
  gain.connect(dest);
  
 ...