Generating sound on the fly with javascript/html5

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

    Using the HTML5 audio element

    Cross-browser generative sustained audio using JavaScript and the audio element isn't currently possible, as Steven Wittens notes in a blog post on creating a JavaScript synth:

    "...there is no way to queue up chunks of synthesized audio for seamless playback".

    Using the Web Audio API

    The Web Audio API was designed to facilitate JavaScript audio synthesis. The Mozilla Developer Network has a Web Based Tone Generator that works in Firefox 4+ [demo 1]. Add these two lines to that code and you have a working synth with generative sustained audio upon keypress [demo 2 - works in Firefox 4 only, click the 'Results' area first, then press any key]:

    window.onkeydown = start;  
    window.onkeyup = stop;
    

    The BBC's page on the Web Audio API is worth reviewing too. Unfortunately, support for the Web Audio API doesn't extend to other browsers yet.

    Possible workarounds

    To create a cross-browser synth at present, you'll likely have to fall back on prerecorded audio by:

    1. Using long prerecorded ogg/mp3 sample tones, embedding them in separate audio elements and starting and stopping them upon keypress.
    2. Embedding an swf file containing the audio elements and controlling playback via JavaScript. (This appears to be the method that the Google Les Paul Doodle employs.)

提交回复
热议问题