1

como fazer a barra de progresso do bootstrap acompanhar o seguimento do video youtube (iframe) implantado na pagina html

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>

2
  • 2
    Mostre o que vc já fez pra gente ter uma ideia. Commented 15/12/2016 às 13:04
  • da uma olhada ae
    – matheus
    Commented 15/12/2016 às 13:39

1 Resposta 1

1

Eu alterei o seu exemplo pra barra de progresso funcionar.

Coloquei uma versão no JSFiddle, eu utilizei o moment.js pra mexer com tempo.

Os métodos e valores foram tirados da documentação da API, Link.

O métodos updateTimerDisplay() updateProgressBar() ficaram implementados assim:

function updateTimerDisplay() {
    if((player.getPlayerState() == 5) || (player.getPlayerState() == -1)) {
        let total = moment.utc(player.getDuration() * 1000);
        $('#duration').text(total.format('mm:ss'));}
        if(player.getPlayerState() == 1) {
        let minutos = moment.utc(player.getCurrentTime() * 1000);

        $('#current-time').text(minutos.format('mm:ss'));
    }
}

function updateProgressBar() {
    if(player.getPlayerState() == 1) {
        let duracao = player.getDuration();
        let atual = player.getCurrentTime();
        atual = parseFloat(atual.toFixed(6));
        let porcentagem = (atual * 100) / duracao;
        $('#progress-bar').css("width", porcentagem + "%").attr("aria-valuenow", porcentagem);
    }
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .