C#播放音乐

C# playing music

我使用 Windows 表单应用创建了一个简单的纸牌游戏。我唯一需要做的就是添加音乐效果。我在 mp3 中录制了一些声音(画一张卡片等),通过 WMPlib 将其添加到游戏中,一切正常,除了一件事。 我想在一个方法的中间播放音乐,而不是在它结束之后 - 我的意思是:

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";
}

发生的情况是代码结束后两种声音一起播放。是否有可能以某种方式管理它以在调用第二种方法之前播放第一种声音? 非常感谢您的帮助 ;)

试试这个:)

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();
}

另外,我建议您避开 Thread.Sleep(XXX),因为它会暂停执行线程。在你睡觉的时候什么都不会发生。