2

我使用 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";
}

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

4

1 回答 1

2

尝试这个 :)

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)因为它会暂停执行线程。睡觉时不会发生任何其他事情。

于 2018-11-29T18:40:12.163 回答