延迟后Javascript播放声音

时间:2018-01-09 07:15:49

标签: javascript jquery html audio

我在javascript中制作了秒表,它接受来自get参数的开始时间。一切正常,但我希望在结束前3秒发出声音。到目前为止我有这个:

HTML:

<form action="timer.php" method="get">
    <select name="hours">
        <?php for($i = 0; $i <= 24; $i++): ?>
            <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
        <?php endfor; ?>
    </select>
    <select name="minutes">
        <?php for($i = 0; $i <= 59; $i++): ?>
            <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
        <?php endfor; ?>
    </select>
    <select name="seconds">
        <?php for($i = 0; $i <= 59; $i++): ?>
            <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
        <?php endfor; ?>
    </select>
    <input type="submit" name="submit" value="submit">
</form>

<div class="stopwatch">
    <a href="javascript:;" class="start-stopwatch">Start stopwatch</a><br>
    <a href="javascript:;" class="stop-stopwatch">Stop stopwatch</a><br>
    <span class="hours"></span>:<span class="minutes"></span>:<span class="seconds"></span>
</div>

Javasciprt:

// GetParams class to parse $_GET[]
    var GetParams = {
        getSearchParameters: function() {
            var prmstr = window.location.search.substr(1);
            return prmstr != null && prmstr != "" ? this.transformToAssocArray(prmstr) : {};
        },

        transformToAssocArray: function( prmstr ) {
            var params = {};
            var prmarr = prmstr.split("&");
            for ( var i = 0; i < prmarr.length; i++) {
                var tmparr = prmarr[i].split("=");
                params[tmparr[0]] = tmparr[1];
            }
            return params;
        }
    };

    var stopWatch = {
        TimerID : null,
        startHours   : parseInt(GetParams.getSearchParameters().hours),
        startMinutes : parseInt(GetParams.getSearchParameters().minutes),
        startSeconds : parseInt(GetParams.getSearchParameters().seconds),
        totalSeconds : parseInt(GetParams.getSearchParameters().seconds) + parseInt(GetParams.getSearchParameters().minutes) * 60 + parseInt(GetParams.getSearchParameters().hours) * 3600,

        changeTimer: function () {
            this.TimerID = setInterval(() => this.timerTick(), 1000);
            $('.start-stopwatch').hide();
        },

        timerTick: function ()
        {
            this.totalSeconds--;
            var hours   = Math.floor(this.totalSeconds / 3600);
            var minutes = Math.floor(this.totalSeconds / 60) - (hours * 60);
            var seconds = this.totalSeconds - (minutes * 60) - (hours * 3600);

            if (hours < 10)
                hours = "0" + hours;

            if (minutes < 10)
                minutes = "0" + minutes;

            if (seconds < 10)
                seconds = "0" + seconds;

            $('.stopwatch .hours').text(hours);
            $('.stopwatch .minutes').text(minutes);
            $('.stopwatch .seconds').text(seconds);

            if (this.totalSeconds === 0)
            {
                clearInterval(this.TimerID);
                new Audio("/sources/sounds/interval.mp3").play();
            }
        },

        isActive: function () {
            return (this.totalSeconds > 0);
        },

        prePopulate: function () {
            var hours   = this.startHours;
            var minutes = this.startMinutes;
            var seconds = this.startSeconds;

            if (hours < 10)
                hours = "0" + hours;

            if (minutes < 10)
                minutes = "0" + minutes;

            if (seconds < 10)
                seconds = "0" + seconds;

            $('.stopwatch .hours').text(hours);
            $('.stopwatch .minutes').text(minutes);
            $('.stopwatch .seconds').text(seconds);
        },

        stopTimer: function () {
            $('.start-stopwatch').show();
            clearInterval(this.TimerID);
        }
    };

使用此代码我得到:

  

未处理的Promise Rejection:NotAllowedError(DOM Exception 35):The   用户代理或平台中不允许请求   当前上下文,可能是因为用户拒绝了权限。

我正在阅读并发现声音必须与用户互动相关联,例如点击。用户必须先点击Start Stopwatch,然后开始倒计时。

我也发现了这个:https://www.sitepoint.com/community/t/count-down-and-make-sound-play-on-click/30270/2

但不知道我应该如何在我的代码中实现它。

3 个答案:

答案 0 :(得分:0)

我知道您可以使用click()功能自动点击某些内容。

所以说你有一个HTML

<button id="mybtn"></button>

你可以通过这样做来点击那个w / JS:

var mybtn = document.getElementById('mybtn');
mybtn.click();
Hopefully that helps!!

答案 1 :(得分:0)

查看函数playAudio()

&#13;
&#13;
$(document).ready(function() {

  var stopWatch = {
    TimerID: null,
    startHours: 0,
    startMinutes: 0,
    startSeconds: 3,
    totalSeconds: 5,

    changeTimer: function() {
      this.TimerID = setInterval(() => this.timerTick(), 1000);
      $('.start-stopwatch').hide();
    },

    timerTick: function() {
      this.totalSeconds--;
      var hours = Math.floor(this.totalSeconds / 3600);
      var minutes = Math.floor(this.totalSeconds / 60) - (hours * 60);
      var seconds = this.totalSeconds - (minutes * 60) - (hours * 3600);

      if (hours < 10)
        hours = "0" + hours;

      if (minutes < 10)
        minutes = "0" + minutes;

      if (seconds < 10)
        seconds = "0" + seconds;

      $('.stopwatch .hours').text(hours);
      $('.stopwatch .minutes').text(minutes);
      $('.stopwatch .seconds').text(seconds);
      //I PUT 3 FOR TESTING PURPOSE
      if (this.totalSeconds === 3) {
        clearInterval(this.TimerID);
        this.playAudio();
      }
    },
    playAudio: function () { 
    //here you can set START,STOP,FILE
      var startSecond = 20,
      stopSecond = 30,
      src ="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" ;
       
      /* you can use createElement() if you need to append 
          a new tag audio at runtime 
      var audioElement = document.createElement('audio'); */
      var audioElement = document.querySelector('audio');
      audioElement.setAttribute('src', src +  '#t=' + startSecond+','+stopSecond);
      audioElement.play();
    },
    isActive: function() {
      return (this.totalSeconds > 0);
    },

    prePopulate: function() {
      var hours = this.startHours;
      var minutes = this.startMinutes;
      var seconds = this.startSeconds;

      if (hours < 10)
        hours = "0" + hours;

      if (minutes < 10)
        minutes = "0" + minutes;

      if (seconds < 10)
        seconds = "0" + seconds;

      $('.stopwatch .hours').text(hours);
      $('.stopwatch .minutes').text(minutes);
      $('.stopwatch .seconds').text(seconds);
    },

    stopTimer: function() {
      $('.start-stopwatch').show();
      clearInterval(this.TimerID);
    }
  };
  
  $(".start-stopwatch").click(()=> stopWatch.changeTimer());
  $(".stop-stopwatch").click(()=> stopWatch.stopTimer());
  //uncomment if you want to play on load of the page
  //stopWatch.playAudio();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form action="timer.php" method="get">
 ........
 <audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"></audio>
</form>

<div class="stopwatch">
  <a href="javascript:;" class="start-stopwatch">Start stopwatch</a>    <br>
   <a href="javascript:;" class="stop-stopwatch">Stop stopwatch</a><br>
   <span class="hours"></span>:
   <span class="minutes"></span>:
   <span class="seconds"></span>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我得到了它的工作:)

  var stopWatch = {
            TimerID : null,
            startHours   : parseInt(GetParams.getSearchParameters().hours),
            startMinutes : parseInt(GetParams.getSearchParameters().minutes),
            startSeconds : parseInt(GetParams.getSearchParameters().seconds),
            totalSeconds : parseInt(GetParams.getSearchParameters().seconds) + parseInt(GetParams.getSearchParameters().minutes) * 60 + parseInt(GetParams.getSearchParameters().hours) * 3600,
            sound        : new Audio("/sources/sounds/interval.mp3"),

            changeTimer: function () {
                this.sound.play();
                this.sound.pause();
                this.TimerID = setInterval(() => this.timerTick(), 1000);
                $('.start-stopwatch').hide();
            },

            timerTick: function ()
            {
                this.totalSeconds--;
                var hours   = Math.floor(this.totalSeconds / 3600);
                var minutes = Math.floor(this.totalSeconds / 60) - (hours * 60);
                var seconds = this.totalSeconds - (minutes * 60) - (hours * 3600);

                if (hours < 10)
                    hours = "0" + hours;

                if (minutes < 10)
                    minutes = "0" + minutes;

                if (seconds < 10)
                    seconds = "0" + seconds;

                $('.stopwatch .hours').text(hours);
                $('.stopwatch .minutes').text(minutes);
                $('.stopwatch .seconds').text(seconds);


                if (this.totalSeconds === 0)
                {
                    this.sound.play();
                    clearInterval(this.TimerID);
                }
            },

            isActive: function () {
                return (this.totalSeconds > 0);
            },

            prePopulate: function () {
                var hours   = this.startHours;
                var minutes = this.startMinutes;
                var seconds = this.startSeconds;

                if (hours < 10)
                    hours = "0" + hours;

                if (minutes < 10)
                    minutes = "0" + minutes;

                if (seconds < 10)
                    seconds = "0" + seconds;

                $('.stopwatch .hours').text(hours);
                $('.stopwatch .minutes').text(minutes);
                $('.stopwatch .seconds').text(seconds);
            },

            stopTimer: function () {
                $('.start-stopwatch').show();
                clearInterval(this.TimerID);
            }
        };