HTML5 video media fragments with Javascript

epignosis567

No one on here ever comments on my questions but maybe this is an easy one? I'm new to coding and I am trying to find a way to navigate a video, as in play the first 10 seconds then stop, play seconds 30-40 then stop, play second 60-30 then stop, etc and to have buttons for it. I have found a tutorial but the buttons don't respond. I've cleaned up the code a bit (don't think I removed anything necessary) and pasted it below. Tutorial link: https://www.sitepoint.com/html5-video-fragments-captions-dynamic-thumbnails/

HTML:

<head>

    <meta charset="UTF-8">
    <title>Untitled Document</title>

    <link href="style.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="script.js"></script>

</head>

<body>

<section class="wrapper">

  <div>
    <video id="frag1" controls preload="metadata">

      <source src="assets/disney.mp4"  type='video/mp4;codecs="avc1.42E01E, mp4a.40.2"' data-original="assets/disney.mp4">

      <source src="assets/disney.mp4" type='video/webm;codecs="vp8, vorbis"' data-original="assets/disney.mp4">

    </video>
    <nav>
      <button data-start="0">Section One</button>
      <button data-start="6">Section Two</button>
      <button data-start="17">Section Three</button>
    </nav>
  </div>

</section>


</body>

</html>

CSS:

@charset "UTF-8";

#main { width: 85%; margin: 1em auto; }

section>div { margin: 0 1.5% 1.5% 0; padding: 1.5%; float: left; background-color: #efefef; }


video { width: 100%; min-height: 430px; }
button { cursor: pointer; }
nav>button { margin: 0.27em; }
nav>button:first-child { margin-left: 0; }
.wrapper { width: 520px; margin: auto; overflow: hidden; text-align: center; }

.p {
  text-align: center;
  padding-top: 120px;
}

Resources 1×0.5×0.25× Rerun

JAVASCRIPT:

function mediaFragOne() 
{
var video, sources, nav, buttons;

video = document.querySelector('video#frag1');
sources = video.getElementsByTagName('source');
nav = document.querySelector('video#frag1+nav');
buttons = nav.getElementsByTagName('button');

for(var i = buttons.length - 1; i >= 0; i--) 
{
    buttons[i].addEventListener('click', function() {
            for (var i = sources.length - 1; i >= 0; i--) {
                sources[i].setAttribute(
                    'src', (sources[i].getAttribute('data-original')
                    .concat('#t=' + this.getAttribute('data-start'))));
                    video.load();
                    video.play();
            };
        });
    }
}
mediaFragOne();
zer00ne

Use Event Delegation when you have multiple tags to click.

  1. Find an ancestor tag (ex. <nav>) that all of the target tags (ex. <a>) have in common. Register the ancestor tag to the event. Now whenever the ancestor tag or its descendant tags triggers the registered event, the callback function bound to the ancestor tag will fire. So essentially that's one event listener for an unlimited number of target tags.

    document.querySelector(ancestor).addEventListener('click', callback);
    
  2. Always have callback function pass the Event Object.

    function callback(event) {...
    
  3. Determine the tag that is the origin of event (button clicked, video time updated, etc...) by referencing Event.target.

    const clicked = event.target
    
  4. In the callback function it should only apply to the target tags and exclude all other tags.

    if (clicked.matches('a')) {...
    ...}
    return false;
    

Details commented in demo

<!DOCTYPE html>
<html>

<head>
  <meta charset='utf-8'>
  <style>
     :root {
      font: 400 2.5vw/1.2 Consolas
    }
    
    .vid {
      display: block;
      margin: 0 auto;
      width: 80vw;
    }
    
    .btns {
      display: flex;
      justify-content: center;
      width: 80vw;
      margin: 0 auto;
    }
    
    a {
      display: block;
      margin: 5px 8px;
      border: 1px solid #000;
      border-radius: 8px;
      text-decoration: none;
      text-align: center;
      padding: 3px 5px;
      width: 15vw;
    }
  </style>
</head>

<body>
  <video class='vid' src='https://storage04.dropshots.com/photos6000/photos/1381926/20170326/005610.mp4' controls></video>
  <nav class='btns'>
    <a href='#/' data-start='00' data-end='10'>00 - 10</a>
    <a href='#/' data-start='10' data-end='20'>10 - 20</a>
    <a href='#/' data-start='20' data-end='30'>20 - 30</a>
    <a href='#/' data-start='30' data-end='40'>30 - 40</a>
  </nav>
  <script>
    // Declare end
    let end;
    // Reference the parent tag of all buttons
    const btns = document.querySelector('.btns');
    // Reference the video
    const vid = document.querySelector('.vid');

    // Register the click event to nav.btns
    btns.addEventListener('click', frag);

    // Register the timeupdate event to video.vid
    vid.addEventListener('timeupdate', stop);

    // Pass Event Object
    function frag(event) {
      // Event.target always points to the clicked button, time-updated video, etc.
      const clicked = event.target;

      // if clicked tag is an <a>...
      if (clicked.matches('a')) {
        // Get the value of its data-start and convert it to a real number
        let start = Number(clicked.dataset.start);
        // Set end to the value of it data-end and convert it to a real number
        end = Number(clicked.dataset.end);
        // Set video current time to value of start
        vid.currentTime = start;
        // Play video
        vid.play();
      }
      // End function
      return false;
    }

    // Pass Event Object
    function stop(event) {
      // Reference the video
      const vid = event.target;

      // if it is a <video>...
      if (vid.matches('video')) {
        // and if that video time is currently at or past the value of end...
        if (vid.currentTime >= end) {
          // Pause video
          vid.pause();
        }
      }
      // End function
      return false;
    }
  </script>
</body>

</html>

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

HTML5 video get currentTime not working with media events javascript addEventListener

javascript передает media EventListener в html (html5) media.currentTime

HTML5 media query video for different viewports (breakpoint not working)

Как показать субтитры на разных языках в HTML5 Video Player через JavaScript?

javascript pass media EventListener to html (html5) media.currentTime

Reveal.js html5 video и javascript - перезапуск воспроизведения видео с начала при проблемах со сменой слайда

Как транслировать видеофайл для тега html5 video

HTML5 Video - какова максимальная скорость воспроизведения?

Определить, воспроизводится ли элемент HTML5 Video

HTML5 <Video> "Цикл" с перерывом или задержкой в несколько секунд

HTML5 Video: автовоспроизведение не работает в лайтбоксе

HTML5 Video // Полностью скрыть элементы управления

HTML5 Video - Как без проблем воспроизвести несколько видео, а затем зациклить последовательность?

Получить номера кадров в HTML5 Video

Как получить отправную точку события поиска в HTML5 Video?

HTML5 Video - как сделать плавное воспроизведение и / или зацикливание нескольких видео?

HTML5 <Video> сбросить видео после слайда

Переключить кнопки воспроизведения / паузы изображения HTML5 Video

HTML5 Video - сделайте паузу на несколько секунд, затем продолжите воспроизведение.

HTML5 video rtsp не работает

HTML5 Video - потоковая передача из потока файлов SQL

HTML5 <video> Элементы управления проигрывателем в Chrome Три точки справа Открыть пустой экран

Отключить воспроизведение / паузу / полноэкранный режим для HTML5 <video> при нажатии на YouTube

Перекодируйте RTSP для тега HTML5 Video в браузере

Как преобразовать анимацию matplotlib в тег HTML5 <video>

Установите HTML5 <video> в качестве фона на указанную высоту div

Необычное поведение HTML5 Video в IOS

HTML5 - Safari не воспроизводит и не распознает <video>

HTML5 Video - запускать события, если currentTime равен установленному времени

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    Резервное копирование / восстановление kafka и zookeeper

  3. 3

    Редактировать существующий файл Excel C # npoi

  4. 4

    Ipython использует% store magic для получения динамического имени

  5. 5

    Как получить список индексов всех значений NaN в массиве numpy?

  6. 6

    Почему бы не выдать ошибку ERROR в тесте Jasmine?

  7. 7

    Дженерики и потоки Java

  8. 8

    Как отфильтровать несколько столбцов в Qtableview?

  9. 9

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  10. 10

    Как изменить значок приложения для проекта libgdx android

  11. 11

    Thymeleaf не отображает значения в проекте Spring Boot

  12. 12

    Unity Проверить, включен ли Toggle

  13. 13

    Airflow не распознает мои настройки подключения S3

  14. 14

    Flutter: Unhandled Exception: FileSystemException: Creation failed, path = 'Directory: '' (OS Error: Read-only file system, errno = 30)

  15. 15

    Bogue étrange datetime.utcnow()

  16. 16

    На графике Matplotlib не отображается легенда

  17. 17

    Создание X509Certificate2 из ECC X509Certificate выдает исключение System.NotSupportedException в C #

  18. 18

    Как добавить фреймворк в файл в папке «Источники» Xcode Playground?

  19. 19

    Выполнение команд PowerShell в программе Java

  20. 20

    Статус HTTP 403 - ожидаемый токен CSRF не найден

  21. 21

    Инструмент для вставки данных, собранных в электронной таблице, в документ Word или PDF

популярныйтег

файл