- 09 August 2014
- javascript
The Web Audio API provides a powerful and versatile system for controlling audio on the Web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning) and much more.
Record Audio and Export to WAV files with Recorder.js
Recorder.js is a library for
recording and exporting the output of Web Audio API. It can be installed using
Bower using the package name recorderjs
(not
recorder.js
, it’s another library). After installation, load the
bower_components/Recorderjs/recorder.js file to your html file to use.
Note: inside the Recorderjs, there is another file named
recorderWorker.js. You will need to specify the path to that file later in
Javascript code. You should run this under an http web server, not through
file:///
.
In the HTML page, I have 2 buttons for start and stop Recording
Next, in the Javascript code, you need to add this to the beginning of your script file to fix the browser compatibility.
The navigator.getUserMedia()
will prompt the user for permission to use media
devices like camera or microphone and then returns a LocalMediaStream
in its
callback.
The AudioContext
is used for creating, processing and decoding audio.
According to
Mozilla, you
need to create an AudioContext
before you can do anything because everything
happens inside a context.
Next, define the function for handling start Recording
Finally, we need another function for stopping Recording and export the WAV file
Now, run a simple http server in the directory that you are working and open the
file to see the result. If you have Nodejs and npm installed, you can install a
simple, zero configuration http server using npm install -g http-server
. The
full source code for this is included at the end of this post.
Record and Stream video
Recording video using Web Audio API is similar to that of recording audio file,
you just need to add the property video: true
to the option object that passed
to getUserMedia()
. This time, there is no need for using Recorder.js since we
don’t need to export anything.
In the HTML code, similarly, add two buttons for start and stop Recording. Add
one <video>
element for playing the video also
The Javascript code is pretty similar to the previous one.
Note: for the example of recording and streaming video, please turn off your speaker or plugin your headphone, otherwise, the sound recorded to the computer will continues to go out through the speaker and the recording step is repeated again endlessly. That will cause some extremely terrible sound that you don’t want to hear.
Demo and Source code
- Live demo is embeded directly inside the below iframe
- Full source code is available on Github web-audio-example.