需要在c#中的秒表应用程序中在特定时间播放声音警报
本文关键字:定时间 播放声音 应用程序 | 更新日期: 2023-09-27 18:16:33
我编写了一个简单的秒表应用程序,它需要在一定的间隔播放声音警报。在15分钟、30分钟和1小时时需要播放声音提示。我已经把声音文件设置为在应用程序启动时播放,但我在如何让它在这些间隔播放上遇到了瓶颈。下面的代码是代码的秒表部分。
还要注意,在这个版本的代码中,我没有初始化声音。任何帮助都将非常感激。
using System;
using System.Diagnostics;
using System.IO;
using System.Media;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;
namespace CiscoSw
{
public partial class SwForm : Form
{
private readonly Stopwatch _sw = new Stopwatch();
internal SwForm()
{
InitializeComponent();
startBtn.Text = @"Start";
UpdateDisplay();
}
private void SwForm_Load(object sender, EventArgs e)
{
currentTimeUtc.Start();
}
private void startBtn_Click(object sender, EventArgs e)
{
if (!_sw.IsRunning)
{
_sw.Start();
stopwatchTimer.Start();
startBtn.Text = @"Stop";
UpdateDisplay();
}
else
{
_sw.Stop();
stopwatchTimer.Stop();
startBtn.Text = @"Start";
}
}
private void resetBtn_Click(object sender, EventArgs e)
{
if (_sw.IsRunning)
{
_sw.Restart();
}
else
{
_sw.Reset();
}
UpdateDisplay();
}
internal void stopwatchTimer_Tick(object sender, EventArgs e)
{
UpdateDisplay();
}
private void UpdateDisplay()
{
stopwatchTimeLabel.Text =
$"{_sw.Elapsed.Hours.ToString("00")}:{_sw.Elapsed.Minutes.ToString("00")}:{_sw.Elapsed.Seconds.ToString("00")}";
}
private void currentTimeUtc_Tick(object sender, EventArgs e)
{
var now = DateTime.UtcNow;
displayCurrentTime.Text = $"{now:M/d/yyyy HHmm Zulu}";
}
}
}
这个代码是用来播放声音的。现在我在资源中只有一个声音文件,一旦我让它正常工作,我将添加其他的。该代码位于项目中的一个单独文件中。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using static System.DateTime;
namespace CiscoSw
{
public class TimerSound
{
public virtual void TimerSoundPlay()
{
var fifteenminSound = new SoundPlayer(Properties.Resources.ResourceManager.GetObject("fifteenminutes") as Stream);
fifteenminSound.Play();
}
}
}
应该可以。我还没有测试代码。我使用System.Windows.Forms.Timer
编辑:我刚刚用较短的时间间隔测试了这个,它工作得很好。我还将MakeSound调用移到了事件的末尾,这样它就不会阻碍计时器的重置。
Timer Timer15 = new Timer();
Timer Timer30 = new Timer();
Timer Timer60 = new Timer();
public void SetupTimers()
{
Timer15.Interval = 15 * 60 * 1000;
Timer30.Interval = 30 * 60 * 1000;
Timer60.Interval = 60 * 60 * 1000;
Timer15.Tick += Timer_Tick;
Timer30.Tick += Timer_Tick;
Timer60.Tick += Timer_Tick;
Timer15.Enabled = true;
Timer30.Enabled = true;
Timer60.Enabled = true;
}
void Timer_Tick(object sender, EventArgs e)
{
Timer timer = sender as Timer;
// Unsubscribe from the current event. Prevents multuple subscriptions.
timer.Tick -= Timer_Tick;
// If 60 minutes then reset all timers.
if (timer.Interval == 60 * 60 * 1000)
{
SetupTimers();
}
//Call sound method here.
MakeSound();
}
一种选择是与秒表并行使用Timer,并在15分钟或任何时间间隔过去时引发计时器上的事件。制作关于那个事件的声音。但是,您不能将事件直接附加到秒表