Search code examples
javascripthtmlsafarimobile-safarihtml5-audio

Audio don't start with timer


Hello I have a little problem with my alarm clock. Everything works normally on PC while mobile (Safari) the timer is ignored. Here is the script:

(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);
})();

The problem is that mobile sound is played from the very beginning and so if I parameter one hour the alarm to ring it nothing happens.

I tried to put audioElement.load (); in the condition if (AlarmTime === timestr) but nothing happens either the music does not start.


Solution

  • What you want do accomplish is not possible because you cannot programmatically play audio/video in most mobile browsers without direct physical interaction from the user (e.g ontouchstart, onclick, etc.). The best you can do is listen for a touchstart event anywhere on the document, call play() on the audio, immediately call pause(), and then wait for the alarm before playing the audio again.