Generating sound on the fly with javascript/html5

前端 未结 7 1881
庸人自扰
庸人自扰 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:22

    You can use the Web Audio API in most browsers now (excepting IE and Opera Mini).

    Try out this code:

    // one context per document
    var context = new (window.AudioContext || window.webkitAudioContext)();
    var osc = context.createOscillator(); // instantiate an oscillator
    osc.type = 'sine'; // this is the default - also square, sawtooth, triangle
    osc.frequency.value = 440; // Hz
    osc.connect(context.destination); // connect it to the destination
    osc.start(); // start the oscillator
    osc.stop(context.currentTime + 2); // stop 2 seconds after the current time

    If you want the volume lower, you can do something like this:

    var context = new webkitAudioContext();
    var osc = context.createOscillator();
    var vol = context.createGain();
    
    vol.gain.value = 0.1; // from 0 to 1, 1 full volume, 0 is muted
    osc.connect(vol); // connect osc to vol
    vol.connect(context.destination); // connect vol to context destination
    osc.start(context.currentTime + 3); // start it three seconds from now
    

    I got most of this from experimenting in chromium while reading the Web Audio API Working Draft, which I found from @brainjam 's link.

    I hope that helps. Lastly, it is very helpful to inspect the various objects in the chrome inspector (ctrl-shift-i).

提交回复
热议问题