简体   繁体   English

弹出 javascript 警报时播放音频,并在警报关闭时停止播放

[英]Play audio when javascript alert pops up and stop playing when the alert closes

I'm trying to play an audio when a javascript alert pops up and stop playing the audio when the user closes the alert.我正在尝试在弹出 javascript 警报时播放音频,并在用户关闭警报时停止播放音频。 But the audio is not stopping when the user closes the alert.And the alert keeps appearing again and again even after I close it.但是当用户关闭警报时,音频并没有停止。即使在我关闭它之后,警报也会一次又一次地出现。

const audio = new Audio("sounds/Sparkle - Your Name.mp3");
audio.play();
audio.loop = false;
if(!alert("Time for some anime")){
           audio.pause();
}

you can use confirm() instead of alert()你可以使用confirm()而不是alert()

const audio = new Audio("sounds/Sparkle - Your Name.mp3");
audio.play();
audio.loop = false;

function after() {
    audio.pause();
}

if(confirm("Time for some anime"))
    after();
else
    after();

or shorter with confirm("continue to pause")? after(): after();或更短的confirm("continue to pause")? after(): after(); confirm("continue to pause")? after(): after();

you can test it here:你可以在这里测试它:

https://jsfiddle.net/82wsqhuL/2/ https://jsfiddle.net/82wsqhuL/2/

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

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