C#播放音乐

时间:2018-11-29 17:44:24

标签: c# audio-player wmplib

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

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

1 个答案:

答案 0 :(得分: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),因为它会暂停执行线程。睡觉时什么也不会发生。

相关问题