Как заставить YouTube автоматически воспроизводить звук? - PullRequest
0 голосов
/ 07 ноября 2018

Мои редакторы хотели бы, чтобы наши встроенные видео на YouTube начали воспроизводиться в режиме наложения, когда кто-то нажимает на видео.

Мне удалось загрузить видео в модальном наложении и начать воспроизведение. Но я могу заставить их воспроизводиться только после добавления &mute=1 к URL-адресу для вставки YouTube.

Есть ли способ заставить их играть со звуком? В конце концов, мы загружаем видео в модальный режим только после того, как пользователь сообщил о намерении просмотреть его, щелкнув по нему.

Мой HTML:

    <section>
        <div class="container">
            <div class="row">
                <div class="sizer">

                    <div class="overlay" data-toggle="modal" data-target="#ModalBox">

                        <iframe 
                                src="https://www.youtube.com/embed/iRYDYrj3Bfw"
                                frameborder="0"
                                allow="autoplay; encrypted-media"
                                allowfullscreen></iframe>

                    </div>
                </div>
            </div>
        </div>
    </section>

<!-- Modal -->
<div class="modal fade" id="ModalBox" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>        
        <!-- 16:9 aspect ratio -->
        <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item" src="" id="video" allowfullscreen>></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

Мой CSS:

.width {
    width: 560px;
    height: 315px;
}

.sizer {
    width: 560px;
    height: 315px;
}

.overlay {
    position: relative !important;
    cursor: pointer !important;
    width: inherit !important;
}

.overlay:before {
    content: '';
    position: absolute;
    height: 100%;
    width: 100%;
    transition: all 200ms ease-in;
    opacity: 0;
}

.overlay:hover:before {
    background: #999999;
    opacity: 0.3;
}

body {
    margin: 2rem;
}

.modal-dialog {
    max-width: 90%;
    margin: 30px auto;
  }

.modal-body {
    position: relative;
    padding: 0px;
}

.close {
    position: absolute;
    right: -30px;
    top: 0;
    z-index: 999;
    font-size: 2rem;
    font-weight: normal;
    color: #fff;
    opacity: 1;
}

.modal-backdrop {
    opacity: 0.8 !important;
    background: #000;
}

Мой JavaScript:

$(document).ready(function() {

    // get the video src from the youtube iframe
    var $videoSrc = $("iframe").attr("src").split('?')[0];

    // when the modal is opened autoplay it
    $('#ModalBox').on('shown.bs.modal', function (e) { 

        // set the video src to autoplay and not to show related videos.
        var $videoSrcAuto = $videoSrc + "?rel=0&autoplay=1&mute=1";

        $("#video").attr('src',$videoSrcAuto);

    })


    // stop playing the youtube video when modal is closed
    $('#ModalBox').on('hide.bs.modal', function (e) {

        $("#video").attr('src',$videoSrc); 
    }) 

// document ready  
});

Рабочий пример: https://codepen.io/CodeChaos/pen/NExWWo

Обновление 1:

После дальнейших исследований эта проблема, по-видимому, возникает только в Chrome. В Edge и Firefox я могу автоматически воспроизводить видео, даже не отключая звук.

...