Have sound play when alert is triggered

后端 未结 4 1151
盖世英雄少女心
盖世英雄少女心 2020-12-10 15:20

So I have in my javascript an if statement. When it returns true it opens an alert box and plays an alarm sound. The problem is that the sound doesn\'t play until I hit th

相关标签:
4条回答
  • 2020-12-10 15:31

    Preload your audio file in the html beforehand like :

    <audio id="xyz" src="whatever_you_want.mp3" preload="auto"></audio>
    
    if(x > 10)
    {
        document.getElementById('xyz').play();
        alert("Thank you!");
    }
    

    This should surely work.

    0 讨论(0)
  • 2020-12-10 15:48

    You can use:

    var snd = new Audio('/alarm.mp3');    
    snd .onended = function () { alert("Thank you!"); };
    snd .play();
    
    0 讨论(0)
  • 2020-12-10 15:49

    You can try using setTimeout().

    if (x > 10) {
            var snd = new Audio('/alarm.mp3');
            snd.play();
            setTimeout(function(){alert("Thank you!")},6000);
        }
    
    0 讨论(0)
  • 2020-12-10 15:55

    Why not leverage the HTML5 audio events.

    The event ended is triggred once the audio ends playing

    snd.addEventListener('ended', showAlert);
    
    function showAlert() {
     alert("YOUR MESSAGE");
    }
    
    0 讨论(0)
提交回复
热议问题