Bootstrap progress bar tracking video youtube duration deployed to html page

Asked

Viewed 993 times

1

how to make the bootstrap progress bar track the youtube video tracking (iframe) deployed on the html page

var player,
  time_update_interval = 0;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('video-placeholder', {
    width: 600,
    height: 400,
    videoId: 'Xa0Q0J5tOP0',
    playerVars: {
      color: 'white',
      playlist: 'taJ60kskkns,FG0fTKAqZ5g'
    },
    events: {
      onReady: initialize
    }
  });
}

function initialize() {

  // Update the controls on load
  updateTimerDisplay();
  updateProgressBar();

  // Clear any old interval.
  clearInterval(time_update_interval);

  // Start interval to update elapsed time display and
  // the elapsed part of the progress bar every second.
  time_update_interval = setInterval(function() {
    updateTimerDisplay();
    updateProgressBar();
  }, 1000);


  $('#volume-input').val(Math.round(player.getVolume()));
}


// This function is called by initialize()
function updateTimerDisplay() {
  // Update current time text display.
  $('#current-time').text(formatTime(player.getCurrentTime()));
  $('#duration').text(formatTime(player.getDuration()));
}


// This function is called by initialize()
function updateProgressBar() {
  // Update the value of our progress bar accordingly.
  $('#progress-bar').val((player.getCurrentTime() / player.getDuration()) * 100);
}


// Progress bar

$('#progress-bar').on('mouseup touchend', function(e) {

  // Calculate the new time for the video.
  // new time in seconds = total duration in seconds * ( value of range input / 100 )
  var newTime = player.getDuration() * (e.target.value / 100);

  // Skip video to new time.
  player.seekTo(newTime);

});


// Playback

$('#play').on('click', function() {
  player.playVideo();
});


$('#pause').on('click', function() {
  player.pauseVideo();
});


// Sound volume


$('#mute-toggle').on('click', function() {
  var mute_toggle = $(this);

  if (player.isMuted()) {
    player.unMute();
    mute_toggle.text('volume_up');
  } else {
    player.mute();
    mute_toggle.text('volume_off');
  }
});

$('#volume-input').on('change', function() {
  player.setVolume($(this).val());
});

// Other options

$('#speed').on('change', function() {
  player.setPlaybackRate($(this).val());
});

$('#quality').on('change', function() {
  player.setPlaybackQuality($(this).val());
});

// Playlist

$('#next').on('click', function() {
  player.nextVideo()
});

$('#prev').on('click', function() {
  player.previousVideo()
});


$('pre code').each(function(i, block) {
  hljs.highlightBlock(block);
});
<!DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8">
  <title>How to Control YouTube's Video Player with JavaScript</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">


</head>

<body>
  <div id="video-placeholder"></div>
  <div id="controls">
    <ul>
      <li>
        <p><span id="current-time">0:00</span> / <span id="duration">0:00</span>
        </p>
      </li>

      <li>
        <div class="progress">
          <div class="progress">
            <div id="progress-bar" class="progress-bar" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width:20px;">
              <span class="sr-only">70% Complete</span>
            </div>
          </div>
        </div>
      </li>

      <li>
        <i id="play" class="material-icons">play_arrow</i>
      </li>

      <li>
        <i id="pause" class="material-icons">pause</i>
      </li>

    </ul>

  </div>



  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://www.youtube.com/iframe_api"></script>
</body>

</html>

1 answer

2

By Youtube I believe it is not possible. To customize, it is necessary to use the tag <video> HTML5.

Let’s start with Javascript? To make it easier, I used Jquery, but if you want, I can post another one with pure Javascript.

The secret here is the width bar, which should be in percentage.

// Como a barra de progresso do Bootstrap na verdade trabalha com o width em CSS, vamos criar primeiro uma função pra transformar o tempo atual do vídeo em sua correspondente porcentagem
function porcento(valor,maximo){
  // max   = 100
  // valor = x
  // x = valor * 100 / max
  var x = valor * 100 / maximo;
  return x + '%';
}

// Agora começamos o código...
$(document).ready(function(){
  // Criei essa var pra dar play e pause no vídeo ao clicar nele
  var rodando = false;
  // Simples: Ao clicar no vídeo se ele estiver rodando, para ele. Senão, põe ele pra rodar
  $("#meuVideo").click(function(){
    if (rodando){
      this.pause();
      rodando = false;
    } else {
      this.play();
      rodando = true;
    }
  });
  // Aqui tratamos a barra em si:
  // A cada alteração no tempo do vídeo
  $("#meuVideo").on('timeupdate',function(evt){
    // Eu preferi usar variáveis, por motivo de didática
    // Gravo a posição atual
    var estadoAtual = this.currentTime;
    // E o tempo máximo do vídeo
    var duracao = this.duration;
    // Na barra de progresso,
    $('#barra')
      // seto o "valor máximo" para o tempo do vídeo
      .attr('aria-valuemax',duracao)
      // o "valor atual" para o tempo rodado até agora
      .attr('aria-valuenow', estadoAtual)
      // e o principal, o width dela ganha quantos % já foram rodados até aqui (graças a nossa funçãozinha)
      .css('width', porcento(estadoAtual,duracao));
  });
});
<!-- Importando as bibliotecas -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

<!-- Começando o código -->
<div class="container">
  <video id="meuVideo" width="400" height="225" poster="endereco/da/sua-thumbnail.jpeg">
    <source src="endereco/do/seu-video.mp4" type="video/mp4" />
  </video>
  <div class="progress" style="width: 400px">
    <div id="progresso" class="progress-bar" aria-valuemin="0"></div>
  </div>
</div>

HTML is very basic, I just used the tag <video> HTML 5 and the Bootstrap 4 progress bar itself.


Bibliographical references

See also:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.