Open In App

HTML Audio

Last Updated : 26 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The HTML <audio> element is used to add audio content to a webpage, allowing you to play music, sound effects, or other audio files directly in the browser.

Syntax

<audio>
<source src="sample.mp3" type="audio/mpeg">
</audio>.
HTML
<!DOCTYPE html>
<html lang="en">

<body>
	<audio>
		<source src=
"https://media.geeksforgeeks.org/wp-content/uploads/20241009180552641558/sample-12s.mp3" type="audio/mp3">
		<source src="" type="audio/ogg">
	</audio>
</body>

</html>

The <audio> supports the global attributes and event attributes.

Functionality of HTML Audio

HTML Audio Media Types

More Examples of HTML Audio

Basic Autoplay Audio

HTML
<html lang="en">
<body>
	<audio autoplay>
		<source src="https://media.geeksforgeeks.org/wp-content/uploads/20241009180552641558/sample-12s.mp3"
                type="audio/mpeg">
	</audio>
</body>
</html>
  • The <audio> element includes the autoplay attribute, causing the audio to play automatically upon page load.
  • The <source> element specifies the audio file's URL and its MIME type.

To learn more about the HTML audio autoplay attribute, click here Link

Autoplay Audio with Controls and Styling

HTML
<!DOCTYPE html>
<html lang="en">
<head>
	<style>
		audio {
			display: block;
			margin: 20px auto;
			width: 80%;
		}
	</style>
</head>
<body>
	<audio controls autoplay>
		<source src=
"https://media.geeksforgeeks.org/wp-content/uploads/20241009180552641558/sample-12s.mp3" type="audio/mpeg">
	</audio>
</body>
</html>
  • The <audio> element includes both controls and autoplay attributes, providing playback controls to the user while starting the audio automatically.
  • The CSS styles center the audio player on the page and set its width to 80% of the container, enhancing its appearance.

Best Practices for HTML Audio

  • Provide multiple audio formats to ensure compatibility across different browsers.
  • Include the controls attribute to offer users playback options like play, pause, and volume control.

Next Article
Article Tags :

Similar Reads