Audio and video autoplay solution

1. Audio and video automatic playback solution


1.1. Use background

The company project needs to use the audio autoplay function, the first thing that comes to mind is the autoplay attribute.

The easiest way to make content play automatically is to add the autoplay attribute to the element and set the autoplay attribute to true. When the autoplay attribute is true, the media element will automatically start playing as soon as possible after:

  • Pages allow autoplay

  • Media elements have been created during page load

  • Assuming there has been no significant change in network performance or bandwidth, and enough media streams have been received and playback has begun, playback continues without interruption until the end of the media.

However, during the actual operation, it was found that the automatic playback failed, and the following error occurred

Uncaught (in promise) DOMException: play() failed because the user didn’t interact with the document first.

This problem troubled me for a long time, and the process of solving it was very bumpy, so I decided to record the solution. The following is some information I found in the process of solving the problem and the solution to the problem.

2. Why do you want to prohibit automatic playback of audio and video?

Playing audio (or video with an audio track) immediately after a web page has finished loading can accidentally interrupt the user. While autoplaying media files is a useful feature, we should use it sparingly and only when it is needed. To give the user control, browsers often offer various ways to disable autoplay audio. In this article, we will introduce the autoplay function of various media and Web Audio APIs, including some brief introductions on how to use the autoplay function and how to gracefully handle blocking the autoplay function.

The following web functions and APIs may be affected by autoplay blocking:

  • The HTML and element

3. Autoplay strategy of Chrome browser Audio tab

Chrome's autoplay policy is simple:

  • Always allow muted autoplay

  • A top-level frame can delegate autoplay permissions to its iframe to allow autoplay

  • Allow autoplaying of sounds when

  • The user has interacted with the web page, including clicking, touching, pressing a key, and so on. (Use pop-up windows to guide users to click page buttons)

  • On desktop chrome, the user's Media Engagement Index threshold has been crossed, meaning the user has previously played a video with sound. ("Media Engagement Index" is introduced later)

  • A user has added a website to a home screen on a mobile device, or installed a PWA on a desktop.

Since I developed it on the PC side, I can only summarize several solutions based on the above conditions:

  1. Setting the muted attribute of audio to true can achieve mute playback, but this does not meet my needs

  1. 使用iframe, <iframe src = "xxxxx.mp3" allow = "autoplay"/>

  1. Use the audio tag, set autoplay to true, and interact with the page when the playback fails (the pop-up window guides the user to click) to achieve automatic playback

4. Solutions

Considering that the project also needs to implement other functions on audio, it is more convenient to use the third solution.

Now that the third option is chosen, how to check if the autoplay fails? In fact, no event is fired when autoplay fails . There's also no exceptions thrown or callbacks that can be set, and there's not even a marker on the media element to tell you if autoplay is working. Then we can change the direction, instead of only relying on autoplay, but use the play method to play. When the play method is executed, a promise will be returned. We can judge whether the current playback is successful or failed according to the promise, and make a decision after the failure. corresponding solution

constaudioElem=document.querySelector("audio");
letstartPlayPromise=audioElem.play();
if (startPlayPromise!==undefined) {
  startPlayPromise.catch(error=> {
    if (error.name==="NotAllowedError") {
      // 弹窗引导用户与页面做交互,只需要一个简单的按钮即可
      // 记得在按钮上绑定一个带有play()方法的回调函数,以element-plus的组件为例
      ElMessageBox.alert('当前正在自动播放音频', '提示', {
        confirmButtonText: '确认',
        callback: () => {
          audioElem.play();
        },
      })
    } else {
      // Handle a load or playback error
    }
  }).then(() => {
    // Start whatever you need to do only after playback
    // has begun.
  });
}

5. Going further

If the product is very upset after seeing this pop-up window, and insists on letting us realize automatic playback without making the user aware of the need for interaction as much as possible, then what should we do?

Since it can be played normally after interacting with the page, can I bind the interaction event to the document element in advance, can the interaction be completed without the user's knowledge and in a natural way?

// 点击
document.addEventListener('click', () => {
    document.querySelector("audio").play();
});
// 监听鼠标移动的事件
document.addEventListener('mousemove', () => {
    document.querySelector("audio").play();
});

6. MEI Media Engagement Index

In the browsing with chorme as the core, a list of MEI (Media Engagement Index) is set , the length of which is 1000, which is used to measure whether the user is a "loyal user" of the website. When the MEI ranking is high enough, it can be played automatically.

The MEI measures an individual's propensity to consume media on a website. Chrome 's current approach is the ratio of visits to significant media playback events per origin :

  • Media (audio/video) consumption must be greater than 7 seconds.

  • Audio must be present and cannot be muted.

  • A tab with a video is active. (Personal feeling is that you cannot set display: none, visibility: hidden, etc.)

  • Video size (in px) must be larger than 200x140 .

From this, Chrome calculates a media engagement score that is high enough on sites that play media regularly to allow media playback to autoplay on the desktop.

A user's MEI can be found on the chrome://media-engagement internal page.

Author: Withoutmelv Link: https://juejin.cn/post/7073119971735240734

Guess you like

Origin blog.csdn.net/2201_76108770/article/details/128989444