Web Development Course:
TL;DR – In HTML5, audio elements that allow playing sounds can be added to websites.
HTML5 Music Player: Introduction
In HTML4 and earlier versions, audio elements were not supported natively. This means you had to embed a special plugin (e.g., Adobe Flash or Apple Quicktime) to be able to play sound on your website. It wasn't a big deal back then, though: using a lot of dynamic content was barely possible due to slow Internet anyway.
Syntax for HTML5 audio
<audio controls> <source src="audio-tag-example.mp3" type="audio/mpeg"> <source src="audio-tag-sample.wav" type="audio/wav"> <source src="audio-tag-demo.ogg" type="audio/ogg"> Audio tag is not supported in this browser. </audio>
Including <source> tags is necessary: using them, you specify the sources for the audio elements.
You can define multiple sources in different formats to make sure your user's browser supports at least one of them. While the HTML5
<audio> tag itself supports three formats (MP3, Wav and Ogg), the browser support for them differs.
Customizing the HTML5 Audio Player
You can modify the way your player looks and works by including one or multiple tag attributes.
HTML5 Audio Controls
An uncontrollable HTML5 audio player means a terrible user experience. To provide your user with player buttons (also called the HTML5 audio controls), you need to include the
controls attribute within the
<audio> opening tag:
<audio controls> <source src="audio-tag-example.mp3" type="audio/mpeg"> Audio tag is not supported in this browser. </audio>
Using HTML5 audio controls, the user can start and pause the playing sound, raise or lower the volume and skip to a specific part of the track using a slider.
While other attributes are used less commonly, it's still good to be familiar with them in case you need to define a custom type of behavior for your HTML5 audio player.
|autoplay||Makes the audio start playing automatically|
|loop||Makes the audio start playing again when it finishes|
|muted||Makes the player muted by default|
|preload||Instructs the browser what to preload – the whole file (auto), its metadata (metadata) or nothing at all (none)|
HTML5 Audio: Useful Tips
- The text between the
<audio>tags is called the fallback content. The browser will display it if it cannot play the audio. You can add a message to the user or a direct link to the file in here.
- Instead of nesting
<source>tags, you can use the
srcattribute to define the source for the audio. However, it doesn't allow adding multiple sources.
- The HTML5
<audio>is an inline element – however, it doesn't always work well for the design. You can change it to block using CSS.