播放音频文件,如果时间匹配
本文关键字:时间 如果 音频 文件 播放 | 更新日期: 2023-09-27 18:11:30
为什么我不能得到这个音频文件播放时,textboxordertostart.Text
的时间在字符串格式等于系统时间?Textboxordertostart
时间减去DateTimePicker
时间后得到时间
我的代码如下:
SoundPlayer myplayer = new SoundPlayer();
myplayer.SoundLocation= (@"c:'users'woolsvalley'documents'visual studio 2015'Projects'WindowsFormsApplication17'WindowsFormsApplication17'Alarm.wav");
if (DateTime.Now.ToString("hh:mm tt") == textBox_ordertostart.Text)
{
myplayer.Play();
}
抛出一个空异常
string formatString = "yyyHHmmss";
string sample = textBox_ordertostart.Text;
DateTime dt = DateTime.ParseExact(sample, formatString, null);
if (DateTime.Now == dt)
{ myplayer.Play(); }
这个不能正常工作
if (DateTime.Now == DateTime.Parse(textBox_ordertostart.Text))
{ myplayer.Play(); }
您进行比较的方式是一种非常"脆弱"的比较方式,因为它依赖于用户以您期望的格式键入时间。例如,当我测试这个时,我得到了以下结果:
string datetime = DateTime.Now.ToString("hh:mm tt");
// False
Console.WriteLine(datetime == "2:06 PM");
// False
Console.WriteLine(datetime == "2:06 P.M.");
// False
Console.WriteLine(datetime == "2:06");
// False
Console.WriteLine(datetime == "02:06 P.M.");
// True
Console.WriteLine(datetime == "02:06 PM");
如果你把它解析成一个DateTime对象,然后再做ToString,它就不会那么脆弱了。请看这个扩展方法,例如:
public static bool DayMinuteEqual(this string otherDate)
{
// We have to strip out the "." character if present (e.g. 2:05 P.M.)
DateTime otherDateObj = DateTime.Parse(otherDate.Replace(".", ""));
return DateTime.Now.ToString("hh:mm tt") == otherDateObj.ToString("hh:mm tt");
}
现在我得到了我期望的结果:
// True
Console.WriteLine("2:20 PM".DayMinuteEqual());
// True
Console.WriteLine("2:20 P.M.".DayMinuteEqual());
// False, but we'd expect it due to the omission of the "P.M."
Console.WriteLine("2:20".DayMinuteEqual());
// True
Console.WriteLine("02:20 P.M.".DayMinuteEqual());
// True
Console.WriteLine("02:20 PM".DayMinuteEqual());
显然,这并不依赖于用户以"完美"的格式输入日期(但仍然要求他们一些正确格式的感觉)。
谢谢大家。这段代码可以工作,我只需要在更新事件中引发它。
private void timer1_Tick(object sender, EventArgs e)
{ label_time1.Text = DateTime.Now.ToString("hh:mm tt");
mplayer = new SoundPlayer();
mplayer.SoundLocation = (@"c:'users'woolsvalley'documents'visual studio 2015'Projects'WindowsFormsApplication17'WindowsFormsApplication17'Alarm.wav");
if((DateTime.Now.ToString("HH:mm tt") == ((textBox_ordertostart.Text))))
{ mplayer.Play(); }