HTML Background Music

How to Add Background Audio/Music to Your Website

Learn how to add background audio or music files to your website by using the HTML element and its various attributes.

To add background music/audio on your website, you can use the HTML audio element ( ).

Let’s say you have an audio file that you want to play in the background as soon as users visit your website. Here’s the general HTML code required to do that:

audio autoplay> source src="your-audio-file.wav" type="audio/wav" /> audio>

The element’s src attribute accepts both internal and external audio sources as values.

Notice the autoplay attribute. That’s required if you want the audio to start playing as soon as the user enters your webpage.

Demo: to hear an example, turn down the volume on your computer/headphones and click on this demo.

There are three supported audio formats in HTML: MP3, WAV, and OGG. In the element you specify the format in the type attribute:

File Format Media Type
MP3 audio/mpeg
OGG audio/ogg
WAV audio/wav

In this tutorial I use the WAV format, therefore I added the type=»audio/wav» attribute on the element above.

The following is a handful of useful attributes that are built-in to the element, and provide you fine-grained control.

To loop your background audio, you can add the loop attribute:

audio autoplay loop> source src="your-audio-file.wav" type="audio/wav" /> audio>

To mute your background audio, you can add the mute attribute:

audio muted> source src="your-audio-file.wav" type="audio/wav" /> audio>

Why would you use the muted attribute? Well, you might want to disable your audio element’s audio source temporarily and switch it back on again later, without removing the entire element from your webpage.

To add controls (play, pause, etc.), use the controls attribute:

audio controls> source src="your-audio-file.wav" type="audio/wav" /> audio>

Now the user can click play if they want to hear your audio file.

Browser support for audio formats

  • MP3 is supported in all browsers,
  • WAV is supported in all browsers except Edge/IE
  • OGG is supported in all browsers except Edge/IE and Safari

Tip: add an extra to your element as a fallback, in case that your end user uses a browser that doesn’t support your primary file format:

audio controls> source src="your-audio-file.wav" type="audio/wav" /> source src="your-audio-file.mp3" type="audio/mpeg" /> audio>

Now if the end user’s browser doesn’t support the WAV format, it will play the MP3 source instead.

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Источник

HTML Audio

The HTML element is used to play an audio file on a web page.

The HTML Element

To play an audio file in HTML, use the element:

Example

HTML Audio — How It Works

The controls attribute adds audio controls, like play, pause, and volume.

The element allows you to specify alternative audio files which the browser may choose from. The browser will use the first recognized format.

The text between the tags will only be displayed in browsers that do not support the

HTML Autoplay

To start an audio file automatically, use the autoplay attribute:

Example

Note: Chromium browsers do not allow autoplay in most cases. However, muted autoplay is always allowed.

Add muted after autoplay to let your audio file start playing automatically (but muted):

Example

Browser Support

The numbers in the table specify the first browser version that fully supports the element.

Element
4.0 9.0 3.5 4.0 10.5

HTML Audio Formats

There are three supported audio formats: MP3, WAV, and OGG. The browser support for the different formats is:

Browser MP3 WAV OGG
Edge/IE YES YES* YES*
Chrome YES YES YES
Firefox YES YES YES
Safari YES YES NO
Opera YES YES YES

HTML Audio — Media Types

HTML Audio — Methods, Properties, and Events

The HTML DOM defines methods, properties, and events for the element.

This allows you to load, play, and pause audios, as well as set duration and volume.

There are also DOM events that can notify you when an audio begins to play, is paused, etc.

For a full DOM reference, go to our HTML Audio/Video DOM Reference.

HTML Audio Tags

Tag Description
Defines sound content
Defines multiple media resources for media elements, such as and

Источник

Музыка и звуки на HTML-странице

currentTime Позиция курсора проигрывателя, double (секунды) duration Длительность воспроизведения, double (секунды); только чтение muted Заглушен ли звук, boolean paused Остановлено ли воспроизведение, boolean volume Уровень громкости, double (от 0 до 1) played Были ли воспроизведены интервалы полностью, возвращает объект TimeRanges seekable Интервалы, которые готовы для немедленного воспроизведения, возвращает объект TimeRanges buffered Возвращает объект TimeRanges буферизованного файла

События тега

durationchange Обновлён атрибут duration ended Воспроизведение остановлено по достижению конца pause Воспроизведение было остановлено (обратите внимание на отсутствие события stop) play Файл начал проигрываться timeupdate Текущая позиция воспроизведения изменилась (обычно каждые 250 мс) volumechange Значение изменилось canplay Файл может быть воспроизведен, но, возможно, потребуется пауза, пока он загружается. canplaythrough При имеющемся темпе скачивания предполагается, что файл может быть проигран от начала до конца без перерыва. progress Браузер показывает состояние проигрывания (обычно каждые 250 мс)

Объект TimeRanges

Содержит данные о частях буферизованных участков медиафайла (один или более — сколько успело буферизоваться) и имеет свойства:

length Число интервалов start(index Начальное время указанного интервала end(index) Конечное время указанного интервала (отсчитывается от начала воспроизведения)

Управление воспроизведением через JavaScript

  

Для создания объекта audio в javascript используется:

Чтобы определить, поддерживается ли данный формат файла в браузере используйте метод canPlayType() , который возвращает одно из 3 значений:

var audio = new Audio(); var canPlayOgg = !!audio.canPlayType && audio.canPlayType('audio/ogg; codecs="vorbis"') != "";
var audio = document.getElementById('my-audio-id'); // получим доступ к объекту audio. audio.canPlayType('audio/ogg'); // или сразу задав кодек: // audio.canPlayType('audio/ogg; codecs="vorbis"');

Как вариант, объект создаётся полностью на Javascript.

Старые форматы вставки музыки:

Пример
  

Поддерживаемые форматы: Ogg Vorbis, WAV PCM, MP3, AAC, Speex (зависит от конкретного браузера).
Подробнее на Wiki: Audio format support

Источник

How To Add Background Music In HTML (Very Simple Examples)

Welcome to a short tutorial on how to add background music in HTML.

The fastest way to add background music to a website is to insert an audio tag at the bottom of the page – .

Yep, it’s that simple, but there are still a couple of things to take note of – Read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

QUICK SLIDES

How To Add Background Music In HTML

TABLE OF CONTENTS

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming .

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

AUDIO MECHANICS

All right, let us now get into more details on the mechanics of the audio background music.

1) BACKGROUND MUSIC EXAMPLE

     

Contents here as usual.

  • Just use the tag, but try to place it near to the bottom of the page – So that the audio loads last and users don’t have to stare at an empty page for long; Let the text and images load first.
  • The autoplay property should be self-explanatory – Automatically start playing when the audio file is loaded.
  • The loop property as well… Automatically loop when the audio has ended.

2) PLAYING MULTIPLE SONGS

   
  1. The usual tag with slightly different properties – Here, we set it to autoplay only, and give it an id .
  2. In the Javascript, we get the HTML tag, and define a playlist .
  3. When the current song has ended, we simply play the next one; When there are no more songs in the playlist, we loop back to the first song.

SUPPORTED FILE FORMATS

The above examples only used the widely supported mp3 file format, but please take note it is also OK to use the many other audio file formats – wav, ogg, webm, flac . But the support of each file format varies from browser to browser – Check out this table on Wikipedia on the supported audio coding formats.

AUTOPLAY IS NOT REALLY RELIABLE

Nope, please don’t get me wrong. The HTML tag is widely supported in all modern browsers, and it should play just fine so long as the user is on a WIFI connection… Meaning, the problem comes when users are on mobile devices or slow/unstable connection.

Every browser will deal with autoplay differently – If the user is on a mobile device, the autoplay will most likely be ignored and not play. Also, users can set the browser to ignore autoplay totally.

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

A NOTE ABOUT &

If you have been poking around the Internet, you might spot some tutorials using and . Please do not use those anymore – They are deprecated and outdated. Stick with the modern instead.

BACKGROUND MUSIC – NOT A GOOD IDEA?

  • Audio files will slow down the loading of the website.
  • It is not really reliable in any case… It can be totally ignored by the browsers, or by the user’s setting.
  • Intrusive. Imagine being in a quiet office or library, and the page suddenly plays loud music.
  • Annoying. The user is listening to something else, and the background music on the page just crosses over.

So yep, not a good idea. Just don’t include any background music, unless it is absolutely required for a good reason.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

Читайте также:  Ru adlist js fixes ru adlist css fixes
Оцените статью