Popcorn.locale

by rwaldron

HTML

<script src="https://static.bocoup.com/js/popcorn.min.js"></script>
<audio id="narration" preload="auto" autobuffer="" controls="">
<source src="https://videos.cdn.mozilla.net/uploads/webmademovies/popcorn101/popcorn101.ogg">
<source src="https://videos.cdn.mozilla.net/uploads/webmademovies/popcorn101/popcorn101.mp3">
</audio>
<video height="180" width="300" id="video"> 
<source src="https://videos.cdn.mozilla.net/uploads/webmademovies/popcorntest.mp4"></source>
<source src="https://videos.cdn.mozilla.net/uploads/webmademovies/popcorntest.ogv"></source>
<source src="https://videos.cdn.mozilla.net/uploads/webmademovies/popcorntest.webm"></source>
</video>

CSS

html{font-family:arial;}

JavaScript

var medias = {
    audio: Popcorn("#narration"),
    video: Popcorn("#video")
  },
  loadCount = 0,
  events = "play pause timeupdate seeking".split(/\s+/g);

// iterate both media sources
Popcorn.forEach(medias, function(media, type) {

  // when each is ready... 
  media.on("canplayall", function() {

    // trigger a custom "sync" event
    this.emit("sync");

    // Listen for the custom sync event...    
  }).on("sync", function() {

    // Once both items are loaded, sync events
    if (++loadCount == 2) {
      // Uncomment this line to silence the video
      //medias.video.mute();

      // Iterate all events and trigger them on the video 
      // whenever they occur on the audio
      events.forEach(function(event) {

        medias.audio.on(event, function() {

          // Avoid overkill events, trigger timeupdate manually
          if (event === "timeupdate") {

            if (!this.media.paused) {
              return;
            }
            medias.video.emit("timeupdate");

            return;
          }

          if (event === "seeking") {
            medias.video.currentTime(this.currentTime());
          }

          if (event === "play" || event === "pause") {
            medias.video[event]();
          }
        });
      });
    }
  });
});