我正在尝试创建一系列按钮,每个按钮都发出声音。从OpenFileDialog函数检索此声音。但是,我遇到了一种声音分配给所有按钮的问题。我知道为什么会这样,但是我不确定如何解决该问题。基本上,我首先为每个按钮分配了相同的算法:
openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileName = openFileDialog.FileName;
}
和:
soundPlayer = new SoundPlayer(fileName);
soundPlayer.Play();
不幸的是,这非常丑陋,所以我决定将每种算法都放在一个方法中,然后仅将方法调用到它们各自的按钮上。像这样:
public void openDialog()
{
openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileName = openFileDialog.FileName;
}
}
private void button27_Click(object sender, EventArgs e)
{
openDialog();
}
public void playDialog()
{
soundPlayer = new SoundPlayer(fileName);
soundPlayer.Play();
}
private void button1_Click(object sender, EventArgs e)
{
playDialog();
}
但是,由于
openDialog()
调用了与接收文件名相同的变量,因此调用openDialog()
的每个按钮都使用相同的变量,因此播放相同的声音。
最佳答案
您必须将fileName设置为Button的“一部分”。您可以通过以下任一方法来实现:
选一个。
例如,使用标签:
public void playDialog(string fileName)
{
soundPlayer = new SoundPlayer(fileName);
soundPlayer.Play();
}
private void button1_Click(object sender, EventArgs e)
{
playDialog((sender as Button).Tag as string);
}
关于c# - C#将不同的文件应用于相同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26577834/