javascript - 播放HTML5video时如何暂停特定的HTML5音频

标签 javascript html audio video

引用http://america.wtf/Shadex

该站点具有自动播放的音频。但是,有一个视频页面。我想拥有它,以便当您播放视频时它会自动暂停音乐

<div id="videos" style="z-index:1" onClick="document.getElementById('sitemusic').pause();"><br />
<div align="center" id="videobox">Splash
<video style="z-index:-1;" width="400" controls>
  <source src="media/videos/splash.mp4" type="video/mp4">
  <source src="media/videos/splash.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>
</div>
</div>

<audio id="sitemusic" controls autoplay>
  <source src="media/turbo_grid.ogg" type="audio/ogg">
  <source src="media/turbo_grid.mp3" type="audio/mpeg">
Your browser does not support the audio element.
  <script>
  var video = document.currentScript.parentElement;
  video.volume = 0.1;
  </script>
</audio>

最佳答案

请参阅下面的更新示例,该示例将:

  • 播放视频时暂停音频
  • 暂停视频时播放音频

  • 请注意,我从video元素中删除了onClick,并且还向id元素中添加了一个明确的<video>,以便直接引用
    <div id="videos" style="z-index:1"><br />
    <div align="center" id="videobox">Splash
    <video style="z-index:-1;" width="400" controls id="video">
        <source src="media/videos/splash.mp4" type="video/mp4">
        <source src="media/videos/splash.ogg" type="video/ogg">
        Your browser does not support HTML5 video.
    </video>
    </div>
    </div>
    
    <audio id="sitemusic" controls autoplay>
      <source src="media/turbo_grid.ogg" type="audio/ogg">
      <source src="media/turbo_grid.mp3" type="audio/mpeg">
      Your browser does not support the audio element.
      <script>
        var audio = document.currentScript.parentElement;
        audio.volume = 0.1;
    
        var video = document.getElementById("video");
        // this event listener reacts to "play" happening on video element and enacts pause on the audio element
        video.addEventListener('play', function (){document.getElementById("sitemusic").pause()},false);
        // this event listener reacts to "pause" happening on video element and enacts play on the audio element
        video.addEventListener('pause', function (){document.getElementById("sitemusic").play()},false);
      </script>
    </audio>
    

    关于javascript - 播放HTML5video时如何暂停特定的HTML5音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38614764/

    相关文章:

    actionscript-3 - 返回到as3中开始的帧时,如何阻止音乐多次播放?

    javascript - 如何在 JQUERY 中查找与文本框关联的每个事件

    javascript - 在 NW.JS 下获取 OSX 中任何类型的唯一标识符

    jquery - 单击占位符不会使输入处于事件状态

    javascript - 在express中使用许多不同的html页面

    html - 仅使用 CSS : How do you center the first line of formatted text and keep the remaining left justified?

    javascript - 如何使用 jQuery 上下文参数?

    javascript - 将图像绘制为 HTML 表格

    python - Mac OSX 的 PyAudiere 替代品?

    ios - AUSampler : referencing external (downloaded) audio files