HTML and CSS Reference
In-Depth Information
Next, add a background color via CSS to indicate a simple presentation for the
canvas
:
<style>
canvas {background: #000;}
</style>
Note that the
width
and
height
values in
canvas
are DOM attributes,
not style attributes. As such, you need to specify them in the markup,
not the CSS, so that the browser knows the dimensions of its drawing
space. See
Chapter 9
for more on
canvas
.
And now for the JavaScript. First, set up an overall function to generate the wave:
<script>
function genWave(){
Inside that function, get both the
audio
and
canvas
elements:
var audio = document.getElementsByTagName("audio")[0];
var canvas = document.getElementsByTagName("canvas")[0];
#shapes
):
var context = canvas.getContext('2d');
Next, add an event listener to gather data about the audio file using methods from the
Mozilla Audio Data API (
https://developer.mozilla.org/en/Introducing_the_Audio_API
audio.addEventListener(
"MozAudioAvailable"
, buildWave, false);
Then, include a private function to build the
canvas
wave drawing, and get the number
of
channels
and
frameBufferLength
:
function buildWave (event){
var channels = audio.mozChannels;
var frameBufferLength = audio.mozFrameBufferLength;
Note that you need to divide
frameBufferLength
by
channels
because
frameBuffer
contains an array of audio samples that are not separated
by channels, but are all delivered together.
Get the
frameBuffer
data:
var fbData = event.frameBuffer;
Set the step increment:
var stepInc = (frameBufferLength / channels) / canvas.width;

