我目前正在用c#编写一个应用程序,该应用程序启动后将在其中播放背景音乐。当我按下静音按钮时,按钮的点击声音和音乐将停止,或者在取消静音时再次播放。
namespace WindowsFormsApp1
{
public partial class mainMenu : Form
{
public bool sound = true; //variable of whether the sound is on or not
System.Media.SoundPlayer bgm = new System.Media.SoundPlayer(@"C:\Users\User\Desktop\HCI\New folder\bgm.wav");
public bool soundval //for other form to access sound variable value
{
get
{
return sound;
}
set
{
sound = value;
}
}
public mainMenu()
{
InitializeComponent();
play();
}
public void play() //function to play music
{
bgm.PlayLooping();
}
public void stop//function to stop music
{
bgm.Stop();
}
private void soundButton_Click(object sender, EventArgs e) //button that mute or unmute the sound (by changing sound value)
{
if (sound)
{
bgm.Stop();
sound = false;
}
else
{
var p2 = new System.Windows.Media.MediaPlayer();
p2.Open(new System.Uri(@"C:\Users\User\Desktop\HCI\New folder\button.wav"));
p2.Play();
play();
sound = true;
}
}
private void easy_Click(object sender, EventArgs e) //proceed to other form
{
if (sound)
{
var p2 = new System.Windows.Media.MediaPlayer();
p2.Open(new System.Uri(@"C:\Users\User\Desktop\HCI\New folder\button.wav"));
p2.Play();
}
Easy game2 = new Easy();
game2.Tag = this;
game2.Show(this);
Hide();
}
}
}
直到此处,该应用程序都可以正常运行。但是,如果我将声音静音并转到其他形式,则音乐会再次播放,如果我按该特定形式上的任何按钮上的任何按钮,按钮声音也会播放。
其他形式的部分代码(easy_Click):
mainMenu mmenu = new mainMenu();
private void thirdchoice_Click(object sender, EventArgs e)
{
if (mmenu.soundval) //to get the value from first form, button sound should play only when value is true
{
var p2 = new System.Windows.Media.MediaPlayer();
p2.Open(new System.Uri(@"C:\Users\User\Desktop\HCI\New folder\button.wav"));
p2.Play();
}
if (ansNum == choice3num) goodnews();
else badnews();
}
不仅在播放音乐,而且还在播放按钮点击声音。继续第二种形式时,声音值似乎设置为true,即使在第一种形式中它值为false。 我在这个问题上停留了很长时间,到处更改,但没有任何效果。 非常感谢有人可以帮助您。谢谢!