【问题标题】:Javascript play sound on click, second button click stop first soundJavascript在点击时播放声音,第二个按钮点击停止第一个声音
【发布时间】:2014-05-20 12:19:50
【问题描述】:

我有这段代码,在按下按钮时它会播放声音,我想要的是当一个声音从第一次点击开始播放时,如果你在它结束之前点击另一个按钮,它会停止第一个并播放你点击的下一个。

任何想法都会很棒。

<!DOCTYPE html>
<head>
<title>Sounds</title>
</head>

<body>

<audio id="sound1" src="sounds/sound1.mp3"></audio>
<audio id="sound2" src="sounds/sound2.mp3"></audio>

<button onclick="document.getElementById('sound1').play()">Sound 1</button><br />
<button onclick="document.getElementById('sound2').play()">Sound 2</button><br />

</body>
</html>

提前致谢。

【问题讨论】:

    标签: javascript audio


    【解决方案1】:

    试试这样的:

    <audio id="sound1" src="sounds/sound1.mp3"></audio>
    <audio id="sound2" src="sounds/sound2.mp3"></audio>
    
    <button onclick="playSound1()">Sound 1</button><br />
    <button onclick="playSound2()">Sound 2</button><br />
    
    <script type="text/javascript">
    var audio1 = document.getElementById('sound1');
    var audio2 = document.getElementById('sound2');
    function playSound1(){
    if (audio1.paused !== true){
        audio1.pause();
        audio2.play();
        }
    else{
        audio2.play();
        }
    }
    function playSound2(){
    if (audio2.paused !== true){
        audio2.pause();
        audio1.play();
        }
    else{
        audio1.play();
        }
    }
    </script>
    

    虽然我建议你在按钮标签上使用addEventListener 方法而不是 onclick 属性,因为它更易于维护。

    谢谢

    【讨论】:

      【解决方案2】:

      将对应音频的 id 放入按钮的 data-target 属性中。在加载时,获取按钮并分配一个点击处理程序 重新加载当前音频,将当前音频元素设置为按钮的目标,并播放当前音频

      【讨论】:

        猜你喜欢
        • 2012-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多