HTML5 Audio Autoplay Loop: Background Music Guide

by .

To create an HTML5 audio autoplay loop background player, you need an <audio> element, the loop attribute and a way for users to adjust or stop the sound. Add autoplay to request an automatic start. Some browsers will still prevent audible media from playing automatically.

Starting and repeating are separate jobs. HTML can repeat a track after it has started, but getting it to begin with sound for every visitor is less predictable. For many websites, a Play button followed by continuous looping is a good place to start.

HTML5 audio autoplay loop background player with a waveform, play button and looping arrows

HTML5 audio autoplay loop: a background music example

A minimal player looks like this:

<audio controls autoplay loop>
  <source src="/media/background-music.mp3" type="audio/mpeg">
  Your browser does not support HTML audio.
</audio>

Replace the example path with your own audio URL. Use an original recording or one you have permission to play, and keep the controls showing. A visitor whose browser blocks autoplay can click Play; anyone wanting silence can click Pause.

The markup is valid even if the player stays quiet. The browser has the final say on whether that automatic start is allowed.

What the audio attributes do

AttributePurpose
autoplayRequests playback as soon as the browser can start it and permits it.
loopRepeats the track when it reaches the end.
controlsDisplays the browser’s audio controls.
mutedSets the initial muted state.
preload="none"Suggests avoiding an audio download before playback is needed.

There is no background attribute for <audio>. The term describes how you use the recording. MDN’s audio element reference lists the supported attributes.

Why background audio autoplay is blocked

Autoplay restrictions are meant to block unwanted sound. Browser settings, previous interactions with your site and the way the player is embedded can affect what happens when somebody opens the page.

Chrome’s autoplay policy, for example, allows audible playback in certain circumstances after a user interacts with the domain. This explains why music may work on a development computer yet do nothing for a new visitor.

Try visiting with a fresh browser profile, then test on a real phone. Check site permissions as well. Your normal browsing environment may already have a history with the site that a new visitor does not share.

Calling play() at page load does not get around these restrictions. A retry timer will not grant permission either. MDN’s autoplay guide explains why starting playback from a script is still subject to browser policy.

Does muted autoplay solve it?

Muted media may be treated more leniently, but it supplies no background music while silent. Removing muted later will not reliably unlock sound. If the goal is for visitors to hear the recording, give them a clear way to start it.

The playsinline attribute belongs to video. Adding it to an audio player will not unlock audible playback on an iPhone.

HTML5 audio autoplay loop with play and pause controls

The recording in this example waits for a visitor to click Play before it starts looping. If JavaScript fails, the native audio controls remain available. The additional button stays hidden until the script has attached its event handlers.

Use the whole example together. Put the script below the HTML and replace /media/background-music.mp3 with the URL of your MP3.

<audio id="background-audio" controls loop preload="none"
       aria-label="Background music">
  <source src="/media/background-music.mp3" type="audio/mpeg">
  Your browser does not support HTML audio.
</audio>

<button id="music-toggle" type="button" hidden
        aria-controls="background-audio">
  Play background music
</button>
<p id="music-status" role="status"></p>

<script>
(() => {
  const audio = document.getElementById("background-audio");
  const button = document.getElementById("music-toggle");
  const status = document.getElementById("music-status");

  if (!audio || !button || !status) return;

  const syncButton = () => {
    button.textContent = audio.paused
      ? "Play background music"
      : "Pause background music";
  };

  button.addEventListener("click", async () => {
    if (!audio.paused) {
      audio.pause();
      return;
    }

    status.textContent = "";
    button.disabled = true;
    try {
      await audio.play();
    } catch (error) {
      status.textContent = error.name === "NotAllowedError"
        ? "Playback was blocked. Check your browser's site permissions."
        : "The audio could not start. Check the file URL and format.";
    } finally {
      button.disabled = false;
      syncButton();
    }
  });

  audio.addEventListener("play", syncButton);
  audio.addEventListener("pause", syncButton);
  audio.addEventListener("error", () => {
    status.textContent = "The audio could not load. Check the file URL and format.";
    syncButton();
  });

  syncButton();
  button.hidden = false;
})();
</script>

Look at where audio.play() runs: inside the click handler, before any unrelated network request or timer. The code handles a rejected playback promise and keeps the button label in step with the native controls.

MDN’s play() documentation distinguishes permission failures such as NotAllowedError from unsupported media errors. Neither error proves that a file is missing.

Use this example once per page. For multiple players, assign unique IDs and update the selectors for each instance.

HTML5 audio autoplay loop in WordPress

In WordPress, begin with the file rather than the script:

  1. Upload your MP3 through Media → Add New and copy the file URL.
  2. Add a Custom HTML block containing the example’s audio element, button and status paragraph.
  3. Replace the sample source with the full HTTPS URL from the Media Library.
  4. Load the JavaScript after the player markup, using your site’s approved script method or a child theme.
  5. Save and preview the page. Test Play and Pause, then let the recording reach its end to check the repeat.

If the script disappears after saving, check account permissions. WordPress’s Custom HTML documentation explains how users without unfiltered_html have disallowed tags removed. Where your editor provides separate HTML and JavaScript panels, put the JavaScript in its own panel without the surrounding <script> tags, if your permissions allow it.

To publish this tutorial, put the examples in Code blocks so readers see them. To install the actual player, use the markup and script as described above.

Fix HTML5 audio autoplay loop problems

SymptomWhat to check
The player works after a click but stays silent on arrivalAutoplay permission is the likely issue. Keep a visible Play control.
The track never starts, even with native controlsOpen the file URL directly and check the Network panel for failed requests.
Playback runs but no sound is audibleCheck the player’s mute setting, tab mute, device volume and audio output.
The wrong file loads on a WordPress pageReplace the example path with the Media Library file URL and clear relevant caches.
A custom button does nothingCheck whether the script was stripped, whether it runs after the markup and whether its IDs match.
Audio stops when the phone locks or the tab changesTest device power management and browser background playback behaviour. HTML cannot guarantee continued playback.

For MP3 audio, use type="audio/mpeg". The server needs to return the recording itself, rather than an HTML error or login page. Use HTTPS media URLs on an HTTPS page. You can offer other source formats, but changing a filename’s extension will not change its encoding. For more on declaring source formats, see our audio MIME-type explainer.

Do not add crossorigin as a fix for every playback problem. Ordinary cross-origin media playback often works without it. Web Audio processing or fetching a file programmatically can require appropriate CORS response headers.

Looping is not the same as a seamless loop

A track can repeat correctly and still make an awkward loop. Silence at the beginning or end, an abrupt edit or encoding padding can reveal the join.

Listen through the whole recording a few times. Remove unwanted silence and prepare an ending that meets the beginning naturally. Replacing loop with an ended event handler will not cure a gap in the recording or guarantee a seamless repeat.

For games or interactive soundscapes that need precise loop points, Web Audio offers another option. An AudioBufferSourceNode can define loop start and end points. You will also need to manage loading and the audio context, while respecting playback permissions.

Keep background music accessible and lightweight

Under WCAG 2.2 audio control, automatically playing audio that lasts more than three seconds needs a way to pause or stop it, or a volume control independent of the overall system volume.

Let visitors choose to start the music and make stopping it simple. Test with a keyboard: can you reach Pause, and can you see which control has focus? Background sound can compete with screen readers. Hiding the only available controls makes that harder to resolve.

Optional music rarely calls for an immediate download. preload="none" supplies that hint, but the browser decides how to use it. Adding autoplay will not prevent the download required for playback. Keep the recording small enough for its purpose and avoid a large player library for one ambient track.

Frequently asked questions

Can an HTML5 audio autoplay loop start with sound?

Sometimes, when browser policy and permissions allow it. No combination of HTML attributes ensures that every visitor will hear autoplayed sound. Give people a manual Play option.

How do I turn off autoplay or looping?

Delete the appropriate attribute. Setting autoplay="false" or loop="false" does not disable these Boolean attributes. In JavaScript, use audio.autoplay = false or audio.loop = false. Disabling autoplay will not stop audio already playing; use audio.pause() for that.

Will music continue when visitors open another page?

A normal full-page navigation replaces the document and its audio element. To keep music playing, a web application needs to preserve its player across route changes. Saving a preference alone will neither keep the music running nor guarantee playback permission on the next page.

Should I hide the audio controls for background music?

Hide native controls only if you supply accessible alternatives and handle loading or playback failures. For a smaller site, keeping the native controls is usually the easiest option.

Join the discussion.

Some HTML is ok

You can use these tags:
<a href="" title="">
<abbr title="">
<b>
<blockquote cite="">
<cite>
<del datetime="">
<em>
<i>
<q cite="">
<strong>

You can also use <code>, and remember to use &lt; and &gt; for brackets.