簡體   English   中英

c# 中的停止聲音

[英]stopping sounds in c#

 private void guna2Button1_Click(object sender, EventArgs e)
    {
        if (guna2CheckBox2.Checked && guna2CheckBox1.Checked)
        {
            
            MessageBox.Show("Please Choose One Box only");

        }
        else
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = Environment.CurrentDirectory;
            ofd.ShowDialog();

            SoundPlayer player = new System.Media.SoundPlayer(ofd.FileName);
            player.Play();
        }
    }

    private void guna2Button2_Click(object sender, EventArgs e)
    {
        
    }
}

你好我正在做一些讓用戶輸入他的wav文件來播放的東西,還有另一個按鈕讓他停止聲音,但不能使用播放器輸入`在此處輸入代碼代碼播放器停止,因為它脫離上下文,知道如何制作guna2Button 在 else 中停止播放的聲音

您應該使 SoundPlayer 成為一個字段(在類級別定義它)。 這使得 class 中的所有方法都可以訪問它。

private SoundPlayer player;

private void guna2Button1_Click(object sender, EventArgs e)
{
    if (guna2CheckBox2.Checked && guna2CheckBox1.Checked)
    {
        MessageBox.Show("Please Choose One Box only");
    }
    else
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.InitialDirectory = Environment.CurrentDirectory;
        ofd.ShowDialog();

        player = new SoundPlayer(ofd.FileName);
        player.Play();
    }
}

private void guna2Button2_Click(object sender, EventArgs e)
{
    //Check if the player is null (not defined yet), otherwise this could cause a NullReferenceException
    if (player != null) {
        player.Stop();
    }
}

了解變量 scope是個好主意,因為這是 C#(以及幾乎所有其他編程語言)的一個非常重要的方面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM