Syncing HTML5 <video> with <audio> playback

前端 未结 6 1462
你的背包
你的背包 2021-01-31 05:23

I am having track from one source, mute, and I\'d like to play background music over it using element. The tracks contain some time critical elements.

What would be th

6条回答
  •  礼貌的吻别
    2021-01-31 05:52

    Here is a simple solution using Popcorn.js inspired by this article.

    $(function(){
    var medias = {
        audio: Popcorn("#narration"),
        video: Popcorn("#video")
      },
      loadCount = 0,
      events = "play pause timeupdate seeking volumechange".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.video.on(event, function() {
    
              // Avoid overkill events, trigger timeupdate manually
              if (event === "timeupdate") {
    
                if (!this.media.paused) {
                  return;
                }
                medias.audio.emit("timeupdate");
    
                return;
              }
    
              if (event === "seeking") {
                  medias.audio.currentTime(this.currentTime());
              }
              
              if (event === "volumechange") {  
            	  if(this.muted()) { 
            		  medias.audio.mute(); 
            	  } else {
            		  medias.audio.unmute(); 
            	  } 
            	  
            	  medias.audio.volume(this.volume());
              }
    
              if (event === "play" || event === "pause") {
                medias.audio[event]();
              }
            });
          });
        }
      });
    });
    });
      	
      	
         
    
    

提交回复
热议问题