Heim  >  Fragen und Antworten  >  Hauptteil

So implementieren Sie die automatische Audiowiedergabe im Chrome-Browser

<p>Die automatische Audiowiedergabe funktioniert in Mozilla, Microsoft Edge und älteren Versionen von Google Chrome, in Google Chrome 67+ ist jedoch aufgrund von Änderungen in der Autoplay-Richtlinie keine automatische Wiedergabe möglich. </p> <p>Sie haben die automatische Wiedergabe blockiert (bis bestimmte im verlinkten Blogbeitrag angegebene Sitzungsbedingungen erfüllt sind). Wie implementiert man die automatische Audiowiedergabe in Google Chrome 67+? </p>
P粉617597173P粉617597173427 Tage vor1280

Antworte allen(1)Ich werde antworten

  • P粉738346380

    P粉7383463802023-08-21 10:33:30

    解决方案#1

    我的解决方案是创建一个iframe

    <iframe src="audio/source.mp3" allow="autoplay" style="display:none" id="iframeAudio">
    </iframe>

    以及audio标签,用于非Chrome浏览器

    <audio autoplay loop  id="playAudio">
        <source src="audio/source.mp3">
    </audio>

    并且在我的script

    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
      if (!isChrome){
          $('#iframeAudio').remove()
      }
      else {
          $('#playAudio').remove() // 为了确保背景中不会有两个音频
      }

    解决方案#2:

    根据@Leonard,还有另一种解决方法

    创建一个不播放任何内容的iframe,只是为了在第一次加载时触发自动播放。

    <iframe src="silence.mp3" allow="autoplay" id="audio" style="display: none"></iframe>

    好的mp3文件来源:silence.mp3

    然后轻松播放你的真实音频文件。

    <audio id="player" autoplay loop>
        <source src="audio/source.mp3" type="audio/mp3">
    </audio>

    个人更喜欢解决方案#2,因为它是一种更干净的方法,不太依赖JavaScript。

    更新于2019年8月

    解决方案#3

    作为另一种选择,我们可以使用<embed>

    对于Firefox 似乎音频自动播放是有效的,所以我们不需要<embed>元素,因为它会创建两个音频同时运行。

    // index.js
    let audioPlaying = true,
        backgroundAudio, browser;
    browser = navigator.userAgent.toLowerCase();
    $('<audio class="audio1" src="audio.mp3" loop></audio>').prependTo('body');
    if (!browser.indexOf('firefox') > -1) {
        $('<embed id="background-audio" src="audio.mp3" autostart="1"></embed>').prependTo('body');
        backgroundAudio = setInterval(function() {
            $("#background-audio").remove();
            $('<embed id="background-audio" src="audio.mp3"></embed>').prependTo('body');
        }, 120000); // 120000是你的音频持续时间,本例中为2分钟。
    }

    如果你的音频有一个切换事件,请确保删除创建的<embed>元素。

    注意:在切换之后,它将从头开始,因为<embed>已经被删除,<audio>元素现在将正常播放。

    $(".toggle-audio").on('click', function(event) {
        audioPlaying = !audioPlaying;
        $("#background-audio").remove();
    
        clearInterval(backgroundAudio);
        if (audioPlaying){
            $(".audio1").play();
            // 播放音频
        }
        else {
            $(".audio1").pause();
        }

    现在确保隐藏这些<audio><embed>元素

    audio, embed {
        position: absolute;
        z-index: -9999;
    }

    注意:diplay: nonevisibility: hidden会使<embed>元素无法工作。

    Antwort
    0
  • StornierenAntwort