twitter-bootstrap 播放视频时暂停 Bootstrap 轮播

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17038699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 17:19:33  来源:igfitidea点击:

Pausing Bootstrap carousel When a Video playing

javascriptjquerytwitter-bootstrapcarousel

提问by Sisir

I have multiple slide with videos and images. Carousel is set to autoplay when loaded. But when someone plays a video and move mouse out of the side it keeps sliding ( as expected ).

我有多个带有视频和图像的幻灯片。轮播设置为加载时自动播放。但是当有人播放视频并将鼠标移出侧面时,它会继续滑动(正如预期的那样)。

How do I keep track of when a video is playing and pause?I have search around Stack Overflow but didn't find similar question.

如何跟踪视频的播放和暂停时间?我搜索了 Stack Overflow,但没有找到类似的问题。

Site admin will add video later on so they could be iframe or html5 video. So, I need a solution that works for both.

站点管理员稍后会添加视频,因此它们可以是 iframe 或 html5 视频。所以,我需要一个对两者都有效的解决方案。

采纳答案by Alex Wright

This worked for me to pause the Bootstrap carousel when a native HTML5 video is playing and play it again when a video is paused or done playing. I'm a total JS novice but I searched around and strung a few things together. I may have made a mistake (likely) but it works for me.

这对我有用,可以在播放原生 HTML5 视频时暂停 Bootstrap 轮播,并在视频暂停或播放完毕时再次播放。我是一个完全的 JS 新手,但我四处搜索并将一些东西串在一起。我可能犯了一个错误(可能)但它对我有用。

I am not calling videos by IDs because I want the action to work on any video playing in the carousel. I have a few in my case.

我不是通过 ID 调用视频,因为我希望该操作适用于轮播中播放的任何视频。我有几个。

Note to change the ID of the carousel to match yours.

请注意更改转盘的 ID 以匹配您的 ID。

<script>
$('video').on('play', function (e) {
    $("#portfolioCarousel").carousel('pause');
});
$('video').on('stop pause ended', function (e) {
    $("#portfolioCarousel").carousel();
});
</script>

回答by Akshay Ransing

$("#myCarousel").carousel('pause'); to stop it $("#myCarousel").carousel(); to start it again http://www.w3.org/2010/05/video/mediaevents.htmlthere many events you should start it again even pause, ended events are fired and pause on play.

$("#myCarousel").carousel('pause'); 阻止它 $("#myCarousel").carousel(); 重新开始 http://www.w3.org/2010/05/video/mediaevents.html有很多事件你应该重新开始甚至暂停,结束的事件被触发并在播放时暂停。

for youtube im not sure about how you integrate it but they do have js api so https://developers.google.com/youtube/js_api_reference#Eventswill show you events that you can listen and do same as u did with html5 video

对于 youtube,我不确定你是如何集成它的,但他们确实有 js api,所以 https://developers.google.com/youtube/js_api_reference#Events会向你展示你可以收听的事件,就像你对 html5 视频所做的一样

回答by nponcian

For Youtube iframe videos to trigger a pause on the sliding of the carousel whenever a video is playing, you need to have an indicator on whether a video is considered "playing". You can achieve this by using the player functionalities of the Youtube iframe API with JavaScript.

为了让 YouTube iframe 视频在播放视频时触发轮播滑动暂停,您需要有一个关于视频是否被视为“正在播放”的指示器。您可以通过使用带有 JavaScript 的 Youtube iframe API 的播放器功能来实现这一点。

Listen to events that involves these states:

侦听涉及这些状态的事件:

  • YT.PlayerState.PLAYING
  • YT.PlayerState.BUFFERING
  • YT.PlayerState.PLAYING
  • YT.PlayerState.BUFFERING

And then control the Bootstrap carousel sliding through .carousel('pause'):

然后控制 Bootstrap 轮播滑过.carousel('pause')

To be able to listen to such events, you can add to your JavaScript a function called "onPlayerStateChange" (as described within the Youtube iframe API):

为了能够监听此类事件,您可以向 JavaScript 添加一个名为“onPlayerStateChange”的函数(如 Youtube iframe API 中所述):

function onPlayerStateChange(event) // triggered everytime ANY iframe video player among the "players" list is played, paused, ended, etc.
{
    // Check if any iframe video is being played (or is currently buffering to be played)
    // Reference: https://developers.google.com/youtube/iframe_api_reference#Events
    if (event.data == YT.PlayerState.PLAYING || event.data == YT.PlayerState.BUFFERING)
    {
        // If any player has been detected to be currently playing or buffering, pause the carousel from sliding
        // .carousel('pause') - Stops the carousel from cycling through items.
        // Reference: https://getbootstrap.com/docs/4.4/components/carousel/#methods
        $('#moviesCarousel').carousel('pause');
    }
    else
    {
        // If there are no currently playing nor buffering videos, resume the sliding of the carousel
        // This means that once the current video is in a state that is not playing (aside from buffering so either it was paused, or has ended, or wasn't totally played), then the carousel would now resume sliding
        $('#moviesCarousel').carousel();
    }
}

For reference, here is the full working HTML (works directly, no modifications needed) :

作为参考,这里是完整的工作 HTML(直接工作,无需修改):

<!doctype html>
<html lang="en">
<head>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
    <!-- Buttons for manually sliding the carousel -->
    <div class="btn-group col-lg-8" role="group" aria-label="Carousel controls">
        <button id="prevMovie" type="button" class="btn btn-danger">Prev</button>
        <button id="nextMovie" type="button" class="btn btn-info">Next</button>
    </div>

    <!-- The carousel containing the Youtube iframe videos -->
    <!-- Remember to add the ?enablejsapi=1 in the Youtube embed link as described in: -->
    <!-- https://developers.google.com/youtube/iframe_api_reference#Example_Video_Player_Constructors -->
    <div id="moviesCarousel" class="carousel slide col-lg-8" data-ride="carousel" data-interval="2000">
        <div class="carousel-inner embed-responsive embed-responsive-16by9"> <!-- embed is used for responsive size regardless of device -->
            <div class="carousel-item embed-responsive-item active">
                <iframe id="katniss" src="https://www.youtube.com/embed/v98Rh9qzmPs?enablejsapi=1" allowfullscreen></iframe>
            </div>
            <div class="carousel-item embed-responsive-item">
                <iframe id="rancho" src="https://www.youtube.com/embed/-MlkASchodc?enablejsapi=1" allowfullscreen></iframe>
            </div>
            <div class="carousel-item embed-responsive-item">
                <iframe id="logan" src="https://www.youtube.com/embed/UgJr0bNmTL8?enablejsapi=1" allowfullscreen></iframe>
            </div>
        </div>
    </div>

    <!-- jQuery first, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    <script>
        $(document).ready(function()
        {
            // Slide the carousel upon button click
            // .carousel('prev') - Cycles to the previous item
            // .carousel('next') - Cycles to the next item.
            // Reference: https://getbootstrap.com/docs/4.4/components/carousel/#methods
            $('#prevMovie').on('click', function() {
                $('#moviesCarousel').carousel('prev');
            });
            $('#nextMovie').on('click', function() {
                $('#moviesCarousel').carousel('next');
            });

            // When a slide occurs, pause the current iframe video that is playing
            // player.pauseVideo():Void - Pauses the currently playing video.
            // Reference: https://developers.google.com/youtube/iframe_api_reference#Playback_controls
            $('#moviesCarousel').on('slide.bs.carousel', function(event) {
                // The variable "players" contain each Youtube Player for each iframe video
                // Reference: https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player
                // event.from - The index of the current video (before the slide occurs)
                //            - It is also the index of the corresponding player for the current video
                // Reference: https://getbootstrap.com/docs/4.4/components/carousel/#events
                players[event.from].pauseVideo();
            });
        });

        // Start of snippet from: https://developers.google.com/youtube/iframe_api_reference
        var tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        var players = []; // would contain 1 player for each iframe video
        function onYouTubeIframeAPIReady()
        {
            var allMovieIframes = document.getElementById("moviesCarousel").getElementsByTagName('iframe');
            for (currentIFrame of allMovieIframes)
            {
                players.push(new YT.Player(
                    currentIFrame.id, // the target iframe video, here it is  either katniss, rancho, or logan
                    { events: { 'onStateChange': onPlayerStateChange } }
                ));
            }
        }
        function onPlayerStateChange(event) // triggered everytime ANY iframe video player among the "players" list is played, paused, ended, etc.
        {
            // Check if any iframe video is being played (or is currently buffering to be played)
            // Reference: https://developers.google.com/youtube/iframe_api_reference#Events
            if (event.data == YT.PlayerState.PLAYING || event.data == YT.PlayerState.BUFFERING)
            {
                // If any player has been detected to be currently playing or buffering, pause the carousel from sliding
                // .carousel('pause') - Stops the carousel from cycling through items.
                // Reference: https://getbootstrap.com/docs/4.4/components/carousel/#methods
                $('#moviesCarousel').carousel('pause');
            }
            else
            {
                // If there are no currently playing nor buffering videos, resume the sliding of the carousel
                // This means that once the current video is in a state that is not playing (aside from buffering so either it was paused, or has ended, or wasn't totally played), then the carousel would now resume sliding
                $('#moviesCarousel').carousel();
            }
        }
        // End of snippet from Youtube iframe API
    </script>

</body>
</html>