0

I'm trying to make a "notification sound" that plays at certain time specified in the app, but for some reason it won't work. If I compare against a time interval it keeps playing the sound in a loop, but I cannot get it to play the sound once at the very moment the time matches.

        System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\Windows\Media\ding.wav");

        private void timer1_Tick(object sender, EventArgs e)
        {
            TimeSpan currentTime = DateTime.Now.TimeOfDay;

            if (currentTime == TimeSpan.Parse("15:00"))
            {
                player.Play();
            }
        }

The timer compares current time every 100ms so I don't think it's down to timing but maybe I'm just missing something. Any ideas what's wrong or if I should use a different approach?

  • 1
    Timers aren't that precise - there is probably some millisecond remainder that is failing the comparison. I would "round" the time to the nearest minute (and then pause or stop the timer for a few minutes so it doesn't fire multiple times) – D Stanley Aug 17 '22 at 18:17
  • 1
    Instead of doing this, why not just take the timer you already have, set it to not auto restart, and set the interval to `DesiredTime - DateTime.Now`? Then you don't have to work about comparing at all. Just do what you need when the timer elapses. – Jesse Aug 17 '22 at 18:24
  • Oh wait you're using `System.Threading.Timer` not `System.Timers.Timer`. I would suggest using the latter and do what I described in the above comment. – Jesse Aug 17 '22 at 18:27
  • @Jesse Curious why you suggest using `System.Timers.Timer` rather than `System.Threading.Timer`. – Jim Mischel Aug 17 '22 at 18:33
  • @JimMischel It's just a lot easier to work with. You just set an interval, register the event, and start. You can also explicitly tell it not to restart when it elapses instead of needing to worry about handling it within the callback. – Jesse Aug 17 '22 at 18:40
  • @Jesse Interesting. I find `System.Threading.Timer` easier to use, although that's largely a matter of taste. See https://stackoverflow.com/a/23232308/56778 for my reasoning. Also https://stackoverflow.com/a/25146567/56778. – Jim Mischel Aug 17 '22 at 21:13

0 Answers0