在 javascript 数组中播放音频文件时遇到问题

Trouble playing audio files in javascript array

本文关键字:文件 遇到 问题 音频 播放 javascript 数组      更新时间:2023-09-26

>我正在尝试创建一个按钮,单击该按钮时播放音频文件,然后再次单击时播放数组中的下一个文件。我让它播放,但是当我第二次单击它时,它会播放第一个文件和第二个文件。当我第三次按下它时,它会播放第一、第二和第三。似乎我需要重置某些内容或其他内容才能清除页面的前两个轨道。这是我所拥有的:

    <!DOCTYPE HTML>
    <html>
    <head>
    </head>
    <body>
    <script language="javascript" type="text/javascript">
        audio = new Array('audio1.mp3','audio2.mp3','audio3.mp3');
        index = 0;
        function playSound() {
        if(index<3){
        document.getElementById("start").innerHTML=document.getElementById("start").innerHTML +
        "<embed src='""+audio[index]+"'" hidden='"true'" autostart='"true'" loop='"false'" />";
        index++;
        }
        else{ index = 0;
        document.getElementById("start").innerHTML=document.getElementById("start").innerHTML +
        "<embed src='""+audio[index]+"'" hidden='"true'" autostart='"true'" loop='"false'" />";
        index++;
        }

    }
     </script>
                <button id="start" type = "button" onclick="playSound();">Start</button>
    </body>
</html>
function playSound() {
    if(index>=3){
         index = 0;
    }
    document.getElementById("sound").innerHTML=
    "<embed src='""+audio[index]+"'" hidden='"true'" autostart='"true'" loop='"false'" />";
    index++;
}

并添加一个div(您也可以使用css隐藏),我认为这是比将html添加到按钮更好的方法。

<button id="start" type = "button" onclick="playSound();">Start</button>
<div id="sound" style="display:none"></div>

您不断添加越来越多的<embed>元素,但从未删除任何元素。

不要将它们追加到按钮,而是将它们追加到容器,然后在添加另一个容器之前删除它们。