Generating sound on the fly with javascript/html5

前端 未结 7 1885
庸人自扰
庸人自扰 2020-12-12 13:09

Is it possible to generate a constant sound stream with javascript/html5? For example, to generate a perpetual sine wave, I would have a callback function, that would be cal

7条回答
  •  隐瞒了意图╮
    2020-12-12 13:46

    Sure! You could use the tone synthesizer in this demo:

    audioCtx = new(window.AudioContext || window.webkitAudioContext)();
    
    show();
    
    function show() {
      frequency = document.getElementById("fIn").value;
      document.getElementById("fOut").innerHTML = frequency + ' Hz';
    
      switch (document.getElementById("tIn").value * 1) {
        case 0: type = 'sine'; break;
        case 1: type = 'square'; break;
        case 2: type = 'sawtooth'; break;
        case 3: type = 'triangle'; break;
      }
      document.getElementById("tOut").innerHTML = type;
    
      volume = document.getElementById("vIn").value / 100;
      document.getElementById("vOut").innerHTML = volume;
    
      duration = document.getElementById("dIn").value;
      document.getElementById("dOut").innerHTML = duration + ' ms';
    }
    
    function beep() {
      var oscillator = audioCtx.createOscillator();
      var gainNode = audioCtx.createGain();
    
      oscillator.connect(gainNode);
      gainNode.connect(audioCtx.destination);
    
      gainNode.gain.value = volume;
      oscillator.frequency.value = frequency;
      oscillator.type = type;
    
      oscillator.start();
    
      setTimeout(
        function() {
          oscillator.stop();
        },
        duration
      );
    };
    frequency
    
    
    type
    volume
    duration

    Have fun!

    I got the solution from Houshalter here: How do I make Javascript beep?

    You can clone and tweak the code here: Tone synthesizer demo on JS Bin

    Compatible browsers:

    • Chrome mobile & desktop
    • Firefox mobile & desktop Opera mobile, mini & desktop
    • Android browser
    • Microsoft Edge browser
    • Safari on iPhone or iPad

    Not Compatible

    • Internet Explorer version 11 (but does work on the Edge browser)

提交回复
热议问题