I have a button that plays a sound that I load once when i click it. I want to set a timer so that the sound plays every 3 seconds, but i don't want to load the file every time. It should just play the same sound. How do i make the timer work, without having to load the sound file over and over?
EDIT: I know that the s.Play() the timer1_Tick is not going to work...
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
SoundPlayer s = new SoundPlayer(ofd.FileName);
timer1.Start();
s.Play();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
s.Play();
}
Move the sound player out as a class variable:
private SoundPlayer s;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
s = new SoundPlayer(ofd.FileName);
timer1.Start();
s.Play();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
s.Play();
}
Make the SoundPlayer
a private
variable:
private SoundPlayer sp;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
sp = new SoundPlayer(ofd.FileName);
timer1.Start();
sp.Play();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
sp.Play();
}
The answer is to Make it Global and reach it from anywhere
SoundPlayer Global;
int counter;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
SoundPlayer s = new SoundPlayer(ofd.FileName);
timer1.interval=1000;
timer1.Start();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
++counter;
if(counter%3==0)
Global.Play();
//or another aspect if (counter==3){Global.Play();counter=0}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.