To play audio without video, HTML5 uses the audio element . It is similar to the video element in many ways. We can use the following attributes to customize the audio element:
- src: path to audio file
- controls: adds playback controls
- autoplay: sets autoplay
- loop: sets the audio file to repeat
- muted: disables sound by default
- preload: sets file upload mode
All of these attributes will have the same effect as they do on the video element.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Audio in HTML5</title> </head> <body> <audio src="horse.mp3" controls></audio> </body> </html>
Audio in HTML5
Again, depending on the browser, the appearance of the controls may vary. Above is an example for Google Chrome. And in Firefox, they will look a little different:
Support for audio formats
The key point for working with audio is browser support for certain formats. At the moment, the vast majority of browsers support mp3. However, if we are unsure that our audio in a certain format will be supported by the user’s browser, then we can use a nested element source and specify audio in other formats:
<audio width="400" height="300" controls> <source src="horse.mp3" type="audio/mpeg"> <source src="horse.m4a" type="audio/aac"> <source src="horse.ogg" type="audio/ogg"> </audio>
As in the case of the element video, here the source element is set with an attribute src with a link to a file and an attribute with a file type.