HTML5 Audio:Beware of the Raptors
Perhaps you're interested in learning to use HTML5 Audio? You've come to the right place, but be careful of the raptors.
Perhaps you're interested in learning to use HTML5 Audio? You've come to the right place, but be careful of the raptors.
Use the element inspector to find what's making noise. You're looking for something to do with audio.
You can use your Firefox, Chrome, or other browser's developer tools to see how the JavaScript works too. This could provide you with some big hints. Go to the Network tab and refresh to look for the name of the JavaScript file.
The HTML element you need uses the <audio>
tag.
Find out more about it at the MDN documentation for the Embed Audio element.
In the JavaScript, you're looking for the method which plays the
audio, so check for
someAudioObject.play()
.
Find out more about the play method at the MDN documentation for the HTML Media Element in JavaScript.
All we need from our HTML is an audio file we can grab.
<audio src="./raptor-call.wav"></audio>
The usual rules apply for relative paths. In this case, we're looking
for a file called raptor-call.wav
in the same folder as
our HTML file. If it exists, we can play it.
The real magic happens here:
const raptorAudio = document.querySelector('audio')
raptorAudio.play()
We're able to select the audio element, then play it. We can control
when the sound plays by running the play()
command on
whichever event we like.
The full JavaScript code for this page is as follows:
We have a few things happening here, such as the timeouts to line up the sound with the appearance of the velociraptors, and the further timeouts to remove them.