[英]C# timer tick with ofd files
我有一个按钮,它播放的声音在单击时会加载一次。 我想设置一个计时器,使声音每3秒播放一次,但我不想每次都加载文件。 它应该只播放相同的声音。 如何使计时器工作,而不必一遍又一遍地加载声音文件?
编辑:我知道timer1_Tick的s.Play()将无法工作...
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();
}
将声音播放器作为类变量移出:
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();
}
将SoundPlayer
设为private
变量:
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();
}
答案是使它成为全球性并从任何地方到达
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}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.