【问题标题】:Stop playing audio when new audio is played播放新音频时停止播放音频
【发布时间】:2015-09-01 03:04:25
【问题描述】:

如果按下按钮,它应该播放新声音并停止当前正在播放的声音。它也应该做到这一点,以便在播放声音时打开“暂停”类。但如果与按钮相关的声音没有播放,则该类是正常的,即“播放”。

//this is the buttons that can be pressed to play sound
<span class="play" sound="sound1.mp3">Play</span>
<span class="play" sound="sound2.mp3">Play</span>
<span class="play" sound="sound3.mp3">Play</span>

<script>
// trying to make it so that the var audio selects sound based on what button was pressed
var audio = document.createElement('sound');
//when a button is pressed plays sound
$(".play").on('click', function(){

if (audio.paused) {
       audio.play();
    }   
    else {
       audio.pause();
    }
    $( this ).toggleClass( "pause" ); // switch to some new css for a pause button
});

// make it so if audio is already playing and another sound is pressed, the audio that is playing is stopped and newly pressed sound plays.
if any other audio is playing{
then that audio.stop and this.audio. that was clicked. play 
}
// make it so the CSS of the already playing button is switched back and the css of the new button is turned to the pause class.
$( that ).toggleClass( "play" );
$( this ).toggleClass( "pause" );
</script>

【问题讨论】:

    标签: javascript jquery audio


    【解决方案1】:

    我会像这样在 span 中嵌入音频元素:

    <span class="play"><audio src="sound1.mp3">Play</audio></span>
    <span class="play"><audio src="sound2.mp3">Play</audio></span>
    <span class="play"><audio src="sound3.mp3">Play</audio></span>
    

    然后做一些 jQuery 魔术

    $(".play").click(function () {
       $(".play").removeClass('pause').addClass('play').pause();
       $(this).addClass('pause').removeClass('play').play();
    });
    

    【讨论】:

    • 嘿,杰克,感谢您的回复,但这并不是我想要做的。我不打算嵌入音频元素。并使其一次只能播放一种声音。
    • 上述实现会导致什么问题?拥有内嵌音频元素只是使用 HTML5 音频的一种简单方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    相关资源
    最近更新 更多