Var muteButton = document.createElement("button") The simplest is a “Mute” button, which uses a very similar pattern to the Play/Pause button: We also need to create controls for the volume of the audio. Note that we’re not trying to make separate functions for “play” and “stop”, but thinking in terms of the activity of the button.
PlayButton.addEventListener("click", player) Next, we have to make the button actually do something: Now we can set the text of any HTML element easily: We’re going to be doing a lot of swapping text inside button elements, so it makes sense to separate that script into a function: Right now, the play button doesn’t actually have any text in it. PlayButton = document.createElement("button") Īdded to the bottom of our HTML page, this script effectively reduces our audio player to a simple element. Var audioPlayer = document.getElementById("audioplayer"),ĪudioTrack = document.getElementById("audiotrack"), Therefore, we remove the default UI only in the context of our script:
If the user doesn’t have JavaScript running, or if the script we’re about to add fails to work, we still want them to have access to basic audio controls. Once you’re satisfied that the audio works, the next task is to create a custom UI for the player. I’ve placed a element around the as we’ll be adding controls within it, together with captions. mp3, along with every other modern browser, I’m using just that codec. Since the latest versions of Firefox now supports. Here, I’m using Track 24 from NIN’s Ghosts III, licensed under Creative Commons:
#Total control html5 audio player basic code#
The result won’t quite be the version shown above, which will be achieved in the articles ahead, but this code will get you significant part of the way there.įirst, let’s ensure we can get an audio file to play on a page. One of the advantages of hosting your own content is the ability to customize everything about it: rather than having to make do with the UI for audio files from SoundCloud, or built-in browser controls, we can make our own using customized HTML5 elements by knowing just a little JavaScript. I’ll demonstrate that approach here, in building the initial prototype of the web audio player I introduced in part 1 of this series. There are advantages to both methods, but the second tends to yield better results.
#Total control html5 audio player basic series#
The second is to create a series of simple test cases: building upwards, proving each step before using the work to generate a final, complete piece. The first is to dive in head-first, building from the top down, squirrelling into problems as they are found and hoping you’ll get everything right. There are two approaches to making almost anything.