音频不以计时器开始

Audio don't start with timer

本文关键字:开始 计时器 音频      更新时间:2023-09-26

你好,我的闹钟出了点小问题。一切正常工作在PC上,而移动(Safari)定时器被忽略。脚本如下:

(function(){
    var audioElement = document.createElement('audio');
audioElement.setAttribute('src',
    'http://tx.sharp-stream.com/icecast.php?i=mos.mp3');
audioElement.load();
var alarmtime ;
var alarmseted = false;
var starttime = null;
var onehour = 1000*60*60;
$("#setalarm").click(function(){
        alarmtime = $("input").val();
  console.log(alarmtime);
  alarmsetted = true;
    });
$("#actual").click(function(){
        audioElement.pause();
  audioElement.currentTime=0;
    });
$("#StartCounting").click(function(){
        starttime = new Date();
    });
$("#StopCounting").click(function(){
        starttime = null;
    });
$("#textbox1").val( new Date(new Date().valueOf() + 1*60*1000).toLocaleTimeString());
setInterval(function(){
        var storage = $("#main");
      var date = new Date();
  var timestr = date.toLocaleTimeString();
  storage.html(timestr);
  if (alarmseted) {
            //storage.html(storage.html() +
        }if (alarmtime === timestr)
  {
            audioElement.play();
    alarmseted = false;
        }if (starttime!== null) {
            storage.html(storage.html() + "<br />" +(new Date(date-starttime-onehour)).toLocaleTimeString());
        //console.log((date-starttime));
        }
    },
    1000);
})();

问题是移动声音从一开始就播放,所以如果我设置一个小时的闹钟响,什么都不会发生。

我试着把audioElement.load ();放到条件if (AlarmTime === timestr)中但是什么也没有发生,音乐也没有开始。

你想要完成的是不可能的,因为你不能编程地播放音频/视频在大多数移动浏览器没有直接的物理交互来自用户(例如ontouchstart, onclick等)。最好的方法是在文档的任何地方监听touchstart事件,在音频上调用play(),立即调用pause(),然后在再次播放音频之前等待警报。