【问题标题】:How to stop sound from playing, or how do I make it play ONCE?如何停止播放声音,或者如何让它播放一次?
【发布时间】:2021-06-24 12:45:59
【问题描述】:

我正在为聊天设置动画,但我只想播放一次通知声音 - 仅在出现第一个灰色聊天时 (#msg4)。但是,如果我再次单击按钮/输入字段,它将再次播放。之后如何让它停止?我尝试了 audio.pause、audio.load...我无法让它工作。

到目前为止,它是这样工作的(单击输入字段以加载消息):https://ixd1231.firebird.sheridanc.on.ca/narrative_sound/chat.html

HTML

<div class="messages" id="chat-window">
  <div class="blue invisible" id="msg1"> Hi! I'm looking for an old friend. She attended Martin Grove a few years ago.</div>
  <div class="blue invisible" id="msg2">Her name is Sam. *insert pic of Sam and MC*</div>
  <div class="blue invisible" id="msg3">Did you know her or her last name by any chance</div><div class="grey" id="msg4" style="display: none">Hello there!</div>
  <div class="grey" id="msg5" style="display: none">Unfortunately, I did not have the pleasure of teaching Sam. Her last name and whereabouts are a mystery to me as well.</div>
<div class="grey" id="msg6" style="display: none">
 However, I do know she was in the photography club. I always saw her carrying a camera, always taking pictures.
      </div>
 
</div>

<div class="input" id="chat-button" onClick="blueMessage()"></div>

JS

var audio = new Audio('Sound.mp3');


function blueMessage() {
    if (HTMLElementsArr.length > 0) {
        HTMLElementsArr.shift().classList.remove('invisible');

    }


    if (!HTMLElementsArr.length) {
        greyMessage();    
    }

}

function greyMessage() {
    setTimeout(show_msg4, 1500);

}

function show_msg4() {
    document.getElementById("msg4").style.display = "block";
    setTimeout(show_msg5, 1500);
    audio.play(); //SOUND PLAY

}

function show_msg5() {
    document.getElementById("msg5").style.display = "block";
    setTimeout(show_msg6, 2500);
    msg5.scrollIntoView({
        behavior: 'smooth'
    });

}

function show_msg6() {
    document.getElementById("msg6").style.display = "block";
    msg6.scrollIntoView({
        behavior: 'smooth'
    });

}

【问题讨论】:

    标签: javascript jquery audio frontend html5-audio


    【解决方案1】:

    创建全局变量,修改show_msg4()里面的值

    var isPlayed = false;
    
    function show_msg4() {
        document.getElementById("msg4").style.display = "block";
        setTimeout(show_msg5, 1500);
        if(!isPlayed){
            audio.play(); //SOUND PLAY
            isPlayed = true;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多