首页 > 解决方案 > 间隔后等待歌曲在 iframe 音频播放器中结束,然后在父级中运行函数

问题描述

我正在尝试制作一个在具有多个音频播放器的页面之间随机播放的本地 html 音频播放器。我希望每 30 分钟发生一次随机播放,但我希望它等到第一个音频播放器完成播放它的曲目,然后再运行随机播放功能。

我无法让主窗口访问 iframe 中的音频播放器,而且我也对如何在 setinterval 命令中调用事件监听器感到困惑。这是我的代码:

主页:

<iframe src="sPLIF.html" height="200" width="900" frameborder="0" id="pmframe" title="PLIF Player"></iframe>

<script>
    var lastSong = null;
    var selection = null;
    var playlist = [
    "PLIF1/plif1.html", 
    "PLIF200703/PLIF200703.html",
    "PLIF200802/PLIF200802.html",
    "PLIF200808/PLIF200808.html",
    "PLIF200816/PLIF200816.html",
    "PLIF200823/PLIF200823.html",  
    "PLIF_Noir/PLIF_Noir.html",
    "PLIF3_Dream/plif3_dream.html", 
    "sPLIF.html"]; 
   
    var player = document.getElementById("pmframe");
    function selectRandom(){
        while(selection == lastSong){
        selection = Math.floor(Math.random() * playlist.length);
    }
        lastSong = selection; 
        player.src = playlist[selection]; 

    }
    
    selectRandom(); 
    setInterval(endSong, 1800000); 

var alto = document.getElementById("pmframe").contentWindow.player;
  
setTimeout(endSong, 1800000); 

function endSong(){
    alto.addEventListener("ended", selectRandom);
}
    
</script>

和一个示例 iframe 页面:

<audio id="alto" autoplay>
<source src="alto.m4a" type="audio/m4a">
</audio>

<audio id="drums" autoplay>
<source src="drums.m4a" type="audio/m4a">
</audio>



<script>
    var lastSong = null;
    var selection = null;
    var playlist = [
    "alto1x.m4a", 
    "alto1x.m4a",    
    "pause.m4a"]; 
    var player = document.getElementById("alto"); 
    player.autoplay=true;
    player.addEventListener("ended", selectRandom);

    function selectRandom(){
        selection = Math.floor(Math.random() * playlist.length);
        lastSong = selection; 
        player.src = playlist[selection]; 
    }

    selectRandom(); 
    player.play(); 
</script>

<script>
    var lastSong2 = null;
    var selection2 = null;
    var playlist2 = ["drums1x.m4a", "drums1x.m4a", "pause30s.m4a"]; 
    var player2 = document.getElementById("drums"); 
    player2.autoplay=true;
    player2.addEventListener("ended", selectRandom2); 

    function selectRandom2(){
        selection2 = Math.floor(Math.random() * playlist2.length);
        lastSong2 = selection2; 
        player2.src = playlist2[selection2]; 
    }

    selectRandom2(); 
    player2.play(); 
</script>

标签: javascriptiframesetintervaladdeventlistener

解决方案


推荐阅读