Динамически изменяемое видео дает запрос play() был прерван новым запросом загрузки

При динамическом изменении видео я получаю следующую ошибку в консоли сервера

(index):71 Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

Я использую следующий код, когда произошли изменения

function playlocalVID()
{
        var player = document.getElementById("video");
        var currentVID = document.getElementById('currentVID');
        var selectedLocalVID = document.getElementById('howtovideo').files[0];
        currentVID.setAttribute('src', URL.createObjectURL(new Blob([selectedLocalVID])));
        player.load();
        player.play();
}

Но когда меняли видео 3 - 4 раза или нажимали на кнопку "Удалить"

я понимаю проблему

Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

Это моя скрипка

https://jsfiddle.net/q3hhk17e/36/

Не могли бы вы, пожалуйста, дайте мне знать, как решить эту проблему.

1 ответ

Решение

Прикреплять canplay событие в #video элемент, внутри playlocalVID() вызов создать Blob URL от File объект, обратите внимание, что не нужно также вызывать Blob() с File объект как параметр; установить ток File.name в #video.dataset; задавать <input type="file"> элемент .value в null за change событие, которое вызывается, если один и тот же файл выбран последовательно; вызов .load() в #video элемент; ждать canplay или же canplaythrough событие будет отправлено в #video элемент; в canplay вызов обработчика события .play() в #video элемент.

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div class="form-group last">
    <label class="control-label col-md-3">How to video</label>
    <div class="col-md-9">
      <div class="fileinput fileinput-new" data-provides="fileinput">
        <figure>
          <video id="video" width="150" height="100" controls>
            <source id='currentVID' src="" type="video/mp4">
          </video>
          <figcaption></figcaption>
        </figure>
        <div class="fileinput-preview fileinput-exists" style="max-width: 200px; max-height: 150px;"></div>
        <div>
          <span class="btn default btn-file">
            <span class="fileinput-new"> Select Video </span>
          <span class="fileinput-exists"> Change </span>
          <input type="file" id="howtovideo" name="howtovideo" accept="video/mp4" autoplay onchange="playlocalVID();" />
          </span>
          <a href="javascript:;" class="btn red fileinput-exists removepic" data-name="removeforhowtovideo" data-dismiss="fileinput"> Remove </a>
        </div>
      </div>
    </div>
  </div>
  <script>
    var player = document.getElementById("video");
    var currentVID = document.getElementById('currentVID');
    var caption = document.querySelector("figcaption");
    var selectedLocalVID = document.getElementById("howtovideo");
     // reference to `Blob URL` to be created at `playLocalVID`
    var url;
     // attach `canplay` event to `player`
    player.addEventListener("canplay", function handleEvent(e) {
      this.play();
      // set `figcaption` to current video `File.name`
      caption.innerHTML = this.dataset.currentVideo;
    });

    function playlocalVID() {
      if (url) {
        console.log(url);
        // if `url` is defined revoke existing `Blob URL`
        URL.revokeObjectURL(url);
      }
      // create `Blob URL` of `File` object
      url = URL.createObjectURL(selectedLocalVID.files[0]);
      // set `.name` of current `File` at `player.dataset.currentVideo`
      player.dataset.currentVideo = selectedLocalVID.files[0].name;
      // reset `input type="file"` event
      selectedLocalVID.value = null;
      // call `.pause()` at `player`
      player.pause();
      // set new `src` at `<source>` element
      currentVID.setAttribute("src", url);
      // call `.load()` on `player`
      // wait for `canplay` event
      player.load();
    }
  </script>
</body>

</html>

Другие вопросы по тегам