-1

我有一个播放声音的按钮,当我单击它时会加载一次。我想设置一个计时器,让声音每 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();
}
4

3 回答 3

1

将声音播放器作为类变量移出:

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();
}
于 2013-07-16T21:23:52.797 回答
1

答案是让它全球化并从任何地方到达它

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}
}
于 2013-07-16T21:37:23.570 回答
1

制作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();
}
于 2013-07-16T21:26:03.820 回答