如何在倒计时播放声音 [英] How to play a sound with the count down

查看:109
本文介绍了如何在倒计时播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows窗体应用程序,可以让我看到倒计时。我想在特定的时间发出警告声。例如,上午11:06。



I have a windows form application that allows me to see count down. I would like to play a warning sound in a specific time. For example at 11:06 am.

var curTime = DateTime.Now.TimeOfDay;
var soundTime= new TimeSpan(11, 06, 0);

......

 if(curTime==soundTime)
{
   SoundPlayer simpleSound = new SoundPlayer(@"c:\Windows\Media\Windows Logon Sound.wav");
   simpleSound.Play();
}





基本上当倒计时时间到达特定时间时,我想播放那个声音文件,但它没有'工作。



Basically when the count down clock reaches the specific time, I wanted to play that sound file however it doesn't work.

推荐答案

OP已确认我在评论中的建议有效



OP has confirmed that my suggestion in a comment works

引用:

这可能是因为curTime也会有毫秒,所以你的测试if(curTime == soundTime)不太可能是真的(达到精确的几率) 0毫秒很苗条!)。请尝试if(curTime> = soundTime)(并记住重置计时器或循环或用于计数的任何东西)

It is probably because curTime will also have milliseconds, so your test if(curTime==soundTime) would be unlikely to be true (Chances of hitting the exact 0 milliseconds is slim!). Try if(curTime>=soundTime) instead (and remember to reset the timer or loop or whatever you are using to count down)



因此OP代码变为


So the OPs code becomes

var curTime = DateTime.Now.TimeOfDay;
var soundTime= new TimeSpan(11, 06, 0);


......

 if(curTime >= soundTime)
            {
                SoundPlayer simpleSound = new SoundPlayer(@"c:\Windows\Media\Windows Logon Sound.wav");
                simpleSound.Play();
            }


这对我有用



This works for me

var soundTime= new TimeSpan(11, 06, 0);
DateTime start = new DateTime(2009, 12, 9, 10, 0, 0); //10 o'clock
DateTime end = new DateTime(2015, 12, 10, 12, 0, 0); //12 o'clock
DateTime curTime = DateTime.Now;
if ((curTime > start) && (curTime < end))

 
 //if(curTime==soundTime)
            {
                System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\Windows\Media\Windows Logon Sound.wav");
                player.Play();
            }


我假设您的代码在计时器中运行(实际上我确定)



I am assuming than your code is running in a timer (actually I am sure)

var soundTime = new TimeSpan(11, 06, 0);

var curDate = DateTime.Now;
if (soundTime.Equals(new TimeSpan(curDate.Hour, curDate.Minute, curDate.Second)))
{
   SoundPlayer simpleSound = new SoundPlayer(@"c:\Windows\Media\Windows Logon Sound.wav");
   simpleSound.Play();
}





如果您的代码块在计时器刻度事件中,if(curTime> = soundTime)将持续开火并失败。



If your code block is in timer tick event, if(curTime >= soundTime) will fire continuously and will fail.


这篇关于如何在倒计时播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆