简体   繁体   English

C#计时器与Ofd文件打勾

[英]C# timer tick with ofd files

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. 我想设置一个计时器,使声音每3秒播放一次,但我不想每次都加载文件。 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... 编辑:我知道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();
}

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: 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();
}

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}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM