C# 播放wav文件后启动秒表
我正在制作秒表,我想在比赛中使用它。我想通过点击按钮1启动我的秒表,以便播放第一个wav文件,然后秒表启动。但是秒表不能启动。这就是我到现在为止所做的C# 播放wav文件后启动秒表,c#,audio,wav,stopwatch,C#,Audio,Wav,Stopwatch,我正在制作秒表,我想在比赛中使用它。我想通过点击按钮1启动我的秒表,以便播放第一个wav文件,然后秒表启动。但是秒表不能启动。这就是我到现在为止所做的 Stopwatch sw = new Stopwatch(); private void button1_Click(object sender, EventArgs e) { new System.Threading.Thread(testMethod).Start(); }
Stopwatch sw = new Stopwatch();
private void button1_Click(object sender, EventArgs e)
{
new System.Threading.Thread(testMethod).Start();
}
private void testMethod(object obj)
{
System.Media.SoundPlayer sp = new System.Media.SoundPlayer(@"D:\...\something.wav");
sp.Play();
}
void OnSoundPlayOver(object sender, EventArgs e)
{
timer1.Start();
timer2.Start();
sw.Start();
}
如果您的要求是:
- 开始按钮,播放声音,然后启动计时器,在屏幕上显示经过的时间
- 停止按钮,停止任何当前计时器,将最后一个值保留在屏幕上
- 在Windows窗体中实现
private Stopwatch _timer = new Stopwatch();
private BackgroundWorker _worker;
private void btnStop_Click(object sender, EventArgs e)
{
CancelExistingBackgroundWorker();
_timer.Stop();
}
private void btnStart_Click(object sender, EventArgs e)
{
CancelExistingBackgroundWorker();
_timer.Reset();
UpdateLabel(0);
_worker = new BackgroundWorker() { WorkerSupportsCancellation = true };
_worker.DoWork += (a, b) =>
{
while (true)
{
if ((a as BackgroundWorker).CancellationPending) return;
ThreadSafeUpdateLabel();
Thread.Sleep(100);
}
};
var soundPlayer = new SoundPlayer("wavfile.wav");
soundPlayer.PlaySync();
_timer.Start();
_worker.RunWorkerAsync();
}
private void ThreadSafeUpdateLabel()
{
if (lblElapsed.InvokeRequired)
{
lblElapsed.Invoke(new Action(() => ThreadSafeUpdateLabel()));
}
else
{
UpdateLabel(_timer.Elapsed.TotalSeconds);
}
}
private void UpdateLabel(double seconds)
{
lblElapsed.Text = seconds.ToString();
}
private void CancelExistingBackgroundWorker()
{
if (_worker != null)
{
_worker.CancelAsync();
_worker.Dispose();
}
}
好的,但你的问题是什么?我忘了告诉你计时器不想启动。有什么建议吗???你怎么知道秒表还没有启动?,
sw.IsRunning=false
和sw.appeased=TimeSpan.Zero
?很抱歉我对c语言编程的了解不多。我看到的是,应该显示timespan的label1上没有变化。当我使用秒表并通过单击按钮1对其进行编程时,它工作得非常好。我看到您正在更新SoundPlayer,但我看不到您将OnSoundPlayOver事件处理程序添加到SoundPlayer的位置