【问题标题】:How to add audio to a 10 second countdown in javascript如何在javascript中将音频添加到10秒倒计时
【发布时间】:2020-11-02 18:20:10
【问题描述】:

第一次在这里发帖,所以要轻松。 我最近的一个项目遇到了一些问题。我正在尝试创建一个倒计时作为登陆页面,每个数字都有声音(如果有人熟悉,街头霸王 2 的音效)。我已经设法让倒计时开始工作,它会工作,但只有点击一个按钮,因为这是我让它工作的唯一方法。

就像我说的那样,这不是预期的效果,因为一旦倒计时结束,我希望它加载主页。另外,关于为每个单独的数字添加声音,我完全不知道从哪里开始!

这是我目前的 JS

    document.addEventListener('DOMContentLoaded', () => {
    const timeLeftDisplay = document.querySelector('#time-left')
    const startBtn = document.querySelector('#start-button')
    let timeLeft = 10

    function countDown (){
        setInterval(function(){
            if(timeLeft <= 0){
                clearInterval(timeLeft = 0)
            }
            timeLeftDisplay.innerHTML = timeLeft
            timeLeft -= 1
        }, 1000)
    }

    startBtn.addEventListener('click', countDown)

} )

这是当前的 HTML

<script type= "text/javascript" src="assets/javascript/script.js"></script>
<title>Bro-nament</title>
</head>
<body>
<div class="container text-center">
    <h1 class="bro-title"> TIME TILL BRO - DOWN</h1>
    <h2 id="time-left"> 10 </h2>
    <button id="start-button"> <i class="fas fa-fist-raised">   Continue?  </i> <i class="fas fa-fist-raised"></i></button>

Current page view

谢谢

【问题讨论】:

    标签: javascript jquery css function audio


    【解决方案1】:

    在您的服务器中,您需要为所有音频文件命名为一个数字,并使用时间变量的值来递增并获取每一秒的文件的 url。

    喜欢:

    • 9.mp3
    • 8.mp3
    • 7.mp3
    • 6.mp3
    • ....

    一旦计数器为 0,你就可以重定向到你想要的 url。

    let time = 10;
    countdown();
    
    function countdown() {
      // we upadate number text
      document.querySelector('#time-left').textContent = --time;
     
      // if count is equal to 0 (end of counter) 
      if (time === 0) {
         time = 10;
         // we redirect to this url
         window.location.href = "http://www.google.com";
         // we stop the loop
         return false;
      }
      
      //console.log(time);
      
      // we set the url of audio file for each seconde
      const audio = new Audio("https://srv-store5.gofile.io/download/RFgvcw/" + time + ".mp3");
      // if you only want one, u dont need the const time
      //const audio = new Audio("https://srv-store5.gofile.io/download/RFgvcw/1.mp3");  
      
      audio.play();
    
      setTimeout(countdown, 1000);
    }
    #time-left {
        font-size: 150px;
        font-weight: bold;
        margin: auto 0;
        text-align: center;
    }
    &lt;div id="time-left"&gt;&lt;/div&gt;

    【讨论】:

    • 这太棒了,我的角度略有不同,但它对我帮助很大。谢谢
    猜你喜欢
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    相关资源
    最近更新 更多