简体   繁体   English

设置间隔播放音频仅循环音频一次?

[英]Set interval play audio only loop audio once?

I have a set interval and within the set interval I have a sound that needs to be played once and once only but the trouble is the sound keeps looping and doesn't stop does anyone have any idea to what I'm doing wrong here is what I have tried: html: 我有一个设定的时间间隔,并且在设定的时间间隔内,我只需要播放一次声音,但是麻烦的是声音一直循环播放并且不停地播放,有人对我在做什么错有任何想法吗?我试过的:html:

<audio id="swoosh">
  <source src="/resources/music/swoosh.mp3" type="audio/mpeg">
</audio>

js: js:

    var swoosh = document.getElementById("swoosh");

    setInterval(function () {
        if ($('.c:contains("01")').length > 0) {
            $(".links #abt").attr("href", "about.html");

            swoosh.addEventListener('ended', function () {
                swoosh.pause();
                swoosh.currentTime = 0;
                swoosh.loop = false;
            }, false);
            swoosh.play();

            //
            if ($('.c:contains("02")').length > 0) {
                $(".links #work").attr("href", "work.html");

                swoosh.addEventListener('ended', function () {
                    swoosh.pause();
                    swoosh.currentTime = 0;
                    swoosh.loop = false;
                }, false);
                swoosh.play();
            }
        }
    }, 10);

The aim is to play the sound when the contents of class="c" changes so if the contents is 01 the audio should play once and then pause or stop then when it changes to 02 it should play again and then stop or pause etc etc Thanks in advance. 目的是在class="c"的内容更改时播放声音,因此,如果内容为01,则音频应播放一次,然后暂停或停止,然后在更改为02时,音频应再次播放,然后停止或暂停,等等。提前致谢。

I think that you're trying to do that. 我认为您正在尝试这样做。 Store in a variable, the "last sound" reproduced and only plays a new one when it has changed. 存储在变量中的“最后声音”被复制,并且仅在更改后播放新声音。 The listener over "ended" event is unnecessary because you only play once per change. 不需要监听“结束”事件,因为每个更改只播放一次。

var swoosh = document.getElementById("swoosh");
var lastPlay = "00";

setInterval(function () {
    var cValue = $('.c').text();
    if (lastPlay != "01" && cValue.indexOf("01") >= 0) {
        $(".links #abt").attr("href", "about.html");
        swoosh.play();
        lastPlay = "01";
    }
    else if (lastPlay != "02" && cValue.indexOf("02") >= 0) {
        $(".links #work").attr("href", "work.html");
        swoosh.play();
        lastPlay = "02";
    }
}, 10);

Other better way was to add a listener to the change event of the ".c" element, it avoids the "query" every 10ms. 另一个更好的方法是向“ .c”元素的change事件添加一个侦听器,它每10毫秒避免一次“ query”。 But I don't have enough code to show you. 但是我没有足够的代码向您展示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM