mediaElement.play() 方法返回一个被拒绝的 Promise

Nik*_*las 10 html javascript html5-video

我无法在移动浏览器上播放我的视频。使用 Safari 远程调试时,我遇到以下问题:

Unhandled Promise Rejection: AbortError: The operation was aborted.

我找到这个解决方案:https://developers.google.com/web/updates/2017/06/play-request-was-interrupted

但我不知道如何在我的代码中使用它来解决问题。

<video muted id="video" class="absolute right-0 bottom-0 min-w-full min-h-full w-auto" controls>
    <source src="/path/to/video.mp4" type="video/mp4">
</video>
Run Code Online (Sandbox Code Playgroud)
let video = document.getElementbyId('video');
let video_cta = document.getElementbyId('video_cta');

//this doesn't fix my problem
var videoPromise = video.play();

if (videoPromise != undefined) {
    videoPromise.then(function(_) {
      video.pause();
      video.currentTime = 0;
  });
}

//start video after click the button
video_cta.addEventListener('click' function() {
    video.play()
})
Run Code Online (Sandbox Code Playgroud)

zer*_*0ne 5

  • 首先,autoplay属性是必需的。

    <video src='...' controls muted自动播放></video>

  • videoPromise引用视频并调用方法时.play(),它将在 Promise 中工作。

    const videoPromise = document.querySelector('video').play();

  • OP 代码中还存在一个依赖项.getElementById()被误用:

    let video = document.getElementyId('video');
    let video_cta = document.getElementyId('video_cta');

  • OP 中提供的Google文章还提到该<source>标签无法reject正确处理:

    使用

    <video src='...'></video>

    不是

    <video> <source src='...'> </video>

  • 这应该会停止错误消息:

    Unhandled Promise Rejection: AbortError: The operation was aborted.

演示 1使用Promiseand 方法.then()演示 2使用async/await. 它被包装async functionIIFE 立即调用函数表达式

演示1

承诺

let cta = document.querySelector('#cta');

const videoPromise = document.querySelector('video').play();

if (videoPromise != undefined) {
  videoPromise.then(_ => {
video.play();
  });
}

cta.addEventListener('click', function() {
  video.play();
});
Run Code Online (Sandbox Code Playgroud)
<video src="https://storage04.dropshots.com/photos6000/photos/1381926/20170326/005609.mp4" id="video" class="absolute right-0 bottom-0 min-w-full min-h-full w-auto" controls autoplay muted></video>
<button id='cta'>CTA</button>
Run Code Online (Sandbox Code Playgroud)

演示2

async/await

let cta = document.querySelector('#cta');

const video = document.querySelector('video');

(function() {
  playMedia();
})();

async function playMedia() {
  try {
    await video.play();
  } catch (err) {}
}

cta.addEventListener('click', function() {
  video.play();
});
Run Code Online (Sandbox Code Playgroud)
<video src="https://storage04.dropshots.com/photos6000/photos/1381926/20170326/005609.mp4" id="video" class="absolute right-0 bottom-0 min-w-full min-h-full w-auto" controls autoplay muted></video>
<button id='cta'>CTA</button>
Run Code Online (Sandbox Code Playgroud)