我在开始时将一个名为playercount的int设置为1并执行以下操作..
private void button2_Click(object sender, EventArgs e)
{
playercount++;
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = "Super Mario Bros.mp3";
if (playercount % 2 == 0)
{
button2.Text = "Music Toggle: ON";
wplayer.controls.play();
}
else
{
wplayer.controls.stop();
button2.Text = "Music Toggle: OFF";
}
}
由于某些原因,音乐停止似乎不起作用。有什么东西我做错了吗?
答案 0 :(得分:0)
每次单击按钮时,您都在创建WindowsMediaPlayer
的新实例。这意味着您的stop()
来电不会影响您在play()
首次点击时创建的播放器。
您需要将播放器创建为类级变量并对其进行操作。
InvernoMuto指出,你playercount
逻辑也有点可疑。简单bool
还不够吗?
private bool musicPlaying = false;
private WMPLib.WindowsMediaPlayer wplayer = null;
private void button2_Click(object sender, EventArgs e)
{
// create player only if necessary
if(wplayer == null)
{
wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = "Super Mario Bros.mp3";
}
// toggle musicPlaying
musicPlaying = !musicPlaying;
if (musicPlaying)
{
button2.Text = "Music Toggle: ON";
wplayer.controls.play();
}
else
{
wplayer.controls.stop();
button2.Text = "Music Toggle: OFF";
}
}