There is not much to look at - we are going to create a button and connect its click event to a function that plays the audio
Screenshot - not the live demo
Step by Step
You can put them both in the body of your page or put the script in the head block. It doesn't matter for this tutorial.
2: Modify the value of the audioUrl variable near the top of the script to point to your audio file.
Note that your audio file must reside on the same machine as your web page.
3: Reload the page and click the button - you should hear the audio played once.
Understanding the Code
The first function returns the AudioContext for your browser. This is the 'container' for all the audio code and data. Currently the name for this varies between browsers and this function handles that variation for you.
Three global variables are defined, one of which is the URL for the audio file that will be played
The document ready is a standard jQuery way to run code once the page has fully loaded. This does three things.
Not all browsers support web audio yet, so the code tries to instantiate a new AudioContext and issues an error if it fails.
Next the code loads the Audio data from the URL, which happens only once, and binds the play_audio to the click of the button that is defined in HTML.
load_audio and play_audio are defined as separate functions.
load_audio sends an Ajax request to fetch the audio file from the URL, decodes audio data contained in the response and places the result in an AudioBuffer in the AudioContext.
play_audio sets up two audio nodes and connects them in order to play the sound. The audioSourceNode is set up to contain the AudioBuffer that has already been loaded with data. This is connected to the destination node, which is typically the output audio device on the user's computer, i.e. their speakers.
The audio is actually played by the noteOn function call.
Web audio scripts can get much more complex than this, so I hope this serves as a gentle introduction to the field.
For more information on the Web Audio API take a look at these resources:
- W3C Web Audio API Specification
- HTML5 Rocks tutorial by Boris Smus
- Web Audio API documentation from Mozilla
Code for this Tutorial
|1 :||tutorial_6_demo_1.html||Live Demo 1|
Share this tutorial
5 : Play an Audio file (Basic)
30 : Visualizing Audio #1 Time Domain (Advanced)
31 : Visualizing Audio #2 Frequency Domain (Advanced)
32 : Visualizing Audio #3 Time Domain Summary (Advanced)
33 : Visualizing Audio #4 Frequency Spectrogram (Advanced)
35 : getUserMedia #1 - Camera Access (Advanced)
Comment on this Tutorial
comments powered by Disqus