简体   繁体   中英

Visual C# SoundPlayer

Hello im new at C# and i want to Change the Color of a Button then play a sound and if the sound is over, then Change the text but if i Start the Program and press the Button the program is freezed and i get a sound and after the sound the color change in green... Sry for my bad english

private void button1_Click(object sender, EventArgs e)
{
    if (Frage.Text.Contains("Was ist Klein, Grün und Rund?"))
    {
        button1.BackColor = System.Drawing.Color.GreenYellow;
        if(button1.BackColor == System.Drawing.Color.GreenYellow)
        {
            System.Media.SoundPlayer playerwin = new System.Media.SoundPlayer();
            playerwin.SoundLocation = @"C:\Wer wird Behindert\winsound.wav";
            playerwin.Load();
            playerwin.Play();
            if (playerwin.IsLoadCompleted)
            {
                playerwin.PlaySync();
                Frage.Text = "Was ist besser?";
            }
        }
    }else if(Frage.Text.Contains("Was ist besser?"))
    {
        button1.BackColor = System.Drawing.Color.Red;
    }
}

PlaySync() use the actual thread so it will block you application If you want it to be non-blocking use Play() instead.

        if (playerwin.IsLoadCompleted)
        {
            playerwin.Play();
            Frage.Text = "Was ist besser?";
        }

More information here : Play()

Play method will create a thread to play sound. I don't see a properties or events, so it's "fire and forget" method.

You can use PlaySync , which is synhcronous and control thread lifetime yourself to know when this method is finished. Use Task to do so and await for it in event handler (mark it with async ), then UI will not be blocked, something like (untested):

async void button1_Click(object sender, EventArgs e)
{
    ...
    var player = new SoundPlayer { SoundLocation = @"C:\Wer wird Behindert\winsound.wav" };
    button1.Enabled = false; // prevent clicks while sound is played
    await Task.Run(() => player.PlaySync()); // next line will execute after sound playing is finished
    button1.Enabled = true;
    Frage.Text = "Was ist besser?";
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM