Nys
Nys

Reputation: 129

C# playing music

I've created a simple card game using Windows form app. The only thing that I need to do is add music effects. I recorded some sounds (draw a card etc.) in mp3, added it to the game via WMPlib and everything works, except one thing. I want to play the music in the middle of a method, not after it ends - what do I mean is this:

private void Button_Click (object sender, EventArgs e)
{
    //code of player 1
    player.URL = @"draw a card.mp3";
    //Immediatelly after that will play player 2
    Player2();
}

void Player2()
{
    //do stuff
    System.Threading.Thread.Sleep(1000);
    //do another stuff
    player.URL = @"draw a card 2.mp3";
}

What happens is that both sounds are played together after the code ends. Is it possible to manage it somehow to play the first sound before the second method is called? Thanks much for any help ;)

Upvotes: 2

Views: 724

Answers (1)

jurasans
jurasans

Reputation: 171

try this :)

private void Button_Click(object sender, EventArgs e)
{
    //code of player 1

    Task.Run(async () => { 
        //this will run the audio and will not wait for audio to end.
        player.URL = @"draw a card.mp3";
    });

    //excecution flow is not interrupted by audio playing so it reaches this line below.
    Player2();
}

also, i would advise u steer clear of Thread.Sleep(XXX) since it pauses the excecuting thread. and nothing else will happen while you are sleeping.

Upvotes: 2

Related Questions