Audio Autoplay

0 views
Skip to first unread message

Nasha Goodridge

unread,
Jul 1, 2024, 7:38:44 AM (5 days ago) Jul 1
to guvorlimus

Automatically starting the playback of audio (or videos with audio tracks) immediately upon page load can be an unwelcome surprise to users. While autoplay of media serves a useful purpose, it should be used carefully and only when needed. In order to give users control over this, browsers often provide various forms of autoplay blocking. In this guide, we'll cover autoplay functionality in the various media and Web Audio APIs, including a brief overview of how to use autoplay and how to work with browsers to handle autoplay blocking gracefully.

Autoplay blocking is not applied to elements when the source media does not have an audio track, or if the audio track is muted. Media with an active audio track are considered to be audible, and autoplay blocking applies to them. Inaudible media are not affected by autoplay blocking.

The term autoplay refers to any feature that causes media to begin to play without the user specifically requesting that playback begin. This includes both the use of HTML attributes to autoplay media as well as the use of JavaScript code to start playback outside the context of handling user input.

From the user's perspective, a web page or app that spontaneously starts making noise without warning can be jarring, inconvenient, or off-putting. Because of that, browsers generally only allow autoplay to occur successfully under specific circumstances.

Otherwise, the playback will likely be blocked. The exact situations that result in blocking, and the specifics of how sites become allowlisted, vary from browser to browser, but the above are good guidelines to go by.

Note: Put another way, playback of any media that includes audio is generally blocked if the playback is programmatically initiated in a tab which has not yet had any user interaction. Browsers may additionally choose to block under other circumstances.

Now that we've covered what autoplay is and what can prevent autoplay from being allowed, we'll look at how your website or app can automatically play media upon page load, how to detect when autoplay fails to occur, and tips for coping when autoplay is denied by the browser.

The simplest way to automatically play content is to add the autoplay attribute to your or element, which sets the autoplay property on the element to true. When autoplay is true, the media will automatically begin to play as soon as possible after the following have occurred:

If autoplay is important for your application, you may need to customize behavior based on whether or not autoplay is allowed, disallowed, or only supported for inaudible content. For example, if your application needs to autoplay a video and you know that the page only allows the autoplay of inaudible content, you can either mute it or supply a video with no audio track. Similarly, if you know that autoplay is not allowed at all, you might provide a default image for the video (using the poster attribute), or choose to defer loading the video until it is requested.

The Navigator.getAutoplayPolicy() method can be used to check the autoplay policy for a type of media feature (i.e. all media elements, or all audio contexts) in a document, or to check whether a specific media element or audio context can autoplay.

The example below shows how you pass the mediaelement string to get the autoplay policy for all media elements in the document (pass audiocontext to get the policy for audio contexts). The code assumes video is an HTMLVideoElement media element using the tag or HTMLVideoElement, and that it is configured to autoplay with audio by default. If autoplay is only allowed for inaudible content, we mute the audio; if autoplay is disallowed, we make sure that a placeholder image is displayed for the video.

The code to test a specific element or audio context is the same, except that you pass in the element or context to test rather than the type string. Here we pass in the video object we want to test.

The autoplay policy for a type may change due to user interaction with the site, page, or a particular element. Similarly, on some browsers the policy for a specific element might change even though the policy for the type has not (for example, on browsers where touching a particular element can allow just that element to autoplay).

No specific event (or other notification) is triggered by autoplay success or failure, so browsers that do not support Navigator.getAutoplayPolicy() have no easy way to determine if autoplay is supported, or to react when it is triggered or not triggered.

One approach is to listen for the first instance of the play event, which is fired on the media element when is resumed after being paused and when autoplay occurs. That means that the first time the play event is fired, you know your media is being started for the first time after the page is opened,

After getting a reference to the video element from the Event object's target, we use it to remove the event listener. This will prevent any future play events from being delivered to the handler. That could happen if the video is paused and resumed by the user or automatically by the browser when the document is in a background tab.

The term "autoplay" also refers to scenarios in which a script tries to trigger the playback of media that includes audio, outside the context of handling a user input event. This is done by calling the media element's play() method.

Note: It is strongly recommended that you use the autoplay attribute whenever possible, because support for autoplay preferences are more widespread for the autoplay attribute than for other means of playing media automatically. It also lets the browser take responsibility for starting playback, letting it optimize the timing of that taking place.

It's much easier to detect a failure to autoplay media when you use the play() method to start it. play() returns a Promise which is resolved once the media successfully begins to play, and is rejected when playback fails to begin (such as if autoplay is denied). When autoplay fails, you likely will want to offer a way for the user to manually tell the browser to ask the user to grant permission to play media.

The first thing we do with the result of play() is make sure it's not undefined. We check for this because in earlier versions of the HTML specification, play() didn't return a value. Returning a promise to allow you to determine success or failure of the operation was added more recently. Checking for undefined prevents this code from failing with an error on older versions of web browsers.

We then add a catch() handler to the promise. This looks at the error's name to see if it's NotAllowedError. This indicates that playback failed due to a permission issue, such as autoplay being denied. If that's the case, we should present a user interface to let the user manually start playback; that's handled here by a function showPlayButton().

In the Web Audio API, a website or app can start playing audio using the start() method on a source node linked to the AudioContext. Doing so outside the context of handling a user input event is subject to autoplay rules.

In addition to the browser-side management and control over autoplay functionality described above, a web server can also express its willingness to allow autoplay to function. The HTTP Permissions-Policy header's autoplay directive is used to control which domains, if any, can be used to autoplay media. By default, the autoplay Permissions Policy is set to self, indicating that autoplay is permitted as they're hosted on the same domain as the document.

You can also specify an empty allowlist (()) to disable autoplay entirely, * to allow autoplay from all domains, or one or more specific origins from which media can be automatically played. These origins are separated by space characters.

Note: The specified Permissions Policy applies to the document and every nested within it, unless those frames include an allow, which sets a new Permissions Policy for that frame and all frames nested within it.

When using the allow attribute on an to specify a Permissions Policy for that frame and its nested frames, you can also specify the value 'src' to allow autoplay of media only from the same domain as that specified by the frame's src attribute.

Adding Fullscreen API permission to the previous example results in a Permissions-Policy header like the following if fullscreen access is allowed regardless of the domain; a domain restriction can be added as well as needed.

A common use case for autoplay is to automatically begin to play a video clip that goes along with an article, an advertisement, or a preview of the page's main functionality. To autoplay videos like these, you have two options: don't have an audio track, or have an audio track but configure the element to mute the audio by default, like this:

This video element is configured to include the user controls (typically play/pause, scrubbing through the video's timeline, volume control, and muting); also, since the muted attribute is included, and the playsinline attribute that is required for autoplay in Safari, the video will autoplay but with the audio muted. The user has the option, however, of re-enabling the audio by clicking on the unmute button in the controls.

Browsers may have preferences that control the way autoplay works, or how autoplay blocking is handled. Here, any such preferences that may be of special significance or importance to you as a web developer are listed. These include any that may aid in testing or debugging as well as any that could be set in a way that you need to be prepared to handle.

A Boolean preference which specifies whether the HTMLMediaElement.allowedToPlay property is exposed to the web. This is currently false by default (except in nightly builds, where it's true by default). If this is false, the allowedToPlay property is missing from the HTMLMediaElement interface, and is thus not present on either or elements.

59fb9ae87f
Reply all
Reply to author
Forward
0 new messages