I have the following tool written for myself in .net Framework 4.8. It's a simple countdown and at zero a MP3-file is playing.
This is working, but only one time. If I restart the countdown, without closing the tool, than the MP3 is not playing anymore at zero, but the catch-Block is not triggert in PlaySound()-Method
Because it's a very tiny tool, I post the complete source code. I hope anyone could say me, why this error happens.
using System;
using System.Windows.Forms;
using NAudio.Wave;
namespace Kumpel_Counter
{
public partial class Form1 : Form
{
private readonly Timer timer;
private readonly IWavePlayer wavePlayer;
private readonly AudioFileReader audioFile;
private readonly TimeSpan originalTime = TimeSpan.Parse("00:30:00");
private TimeSpan currentTime;
private readonly TimeSpan interval = TimeSpan.FromSeconds(1);
private bool isTimerRunning = false;
public Form1()
{
InitializeComponent();
currentTime = originalTime;
timer = new Timer();
timer.Interval = (int)interval.TotalMilliseconds;
timer.Tick += timer1_Tick;
try
{
wavePlayer = new WaveOut();
audioFile = new AudioFileReader("sound.mp3");
wavePlayer.Init(audioFile);
} catch {
MessageBox.Show("\"sound.mp3\" not found.");
}
}
private void cmdStartStop_Click(object sender, EventArgs e)
{
if (!isTimerRunning)
{
if (TimeSpan.TryParseExact(txtSetTime.Text, @"hh\:mm\:ss", null, out currentTime))
{
timer.Start();
isTimerRunning = true;
cmdStartStop.Text = "Stop";
}
else
{
MessageBox.Show("Please use HH:mm:ss");
}
}
else
{
ResetTimer();
}
}
private void txtSetTime_TextChanged(object sender, EventArgs e)
{
if (txtSetTime.Text.Length > 8)
{
txtSetTime.Text = txtSetTime.Text.Substring(0, 8);
txtSetTime.SelectionStart = txtSetTime.Text.Length;
}
else if (txtSetTime.Text.Length == 2 || txtSetTime.Text.Length == 5)
{
txtSetTime.Text += ":";
txtSetTime.SelectionStart = txtSetTime.Text.Length;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (currentTime.TotalSeconds > 0)
{
currentTime = currentTime.Subtract(interval);
txtSetTime.Text = currentTime.ToString(@"hh\:mm\:ss");
}
else
{
timer.Stop();
isTimerRunning = false;
cmdStartStop.Text = "Start";
txtSetTime.Text = originalTime.ToString();
PlaySound();
}
}
private void cmdInfo_Click(object sender, EventArgs e)
{
MessageBox.Show(this, "Version: 1.0", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ResetTimer()
{
timer.Stop();
currentTime = originalTime;
txtSetTime.Text = currentTime.ToString(@"hh\:mm\:ss");
isTimerRunning = false;
cmdStartStop.Text = "Start";
}
private void PlaySound()
{
try
{
wavePlayer.Play();
}
catch (Exception ex)
{
MessageBox.Show($"Error playing MP3: {ex.Message}");
}
}
}
}
I checked my code, but could not find the problem.