如何使用MediaElement播放音频异步?

时间:2013-08-16 02:51:52

标签: c# visual-studio xaml visual-studio-2012

我相信我要做的是异步播放音频。我正在为Windows 8编写一个应用程序,它要求每按一个按钮就播放一个音频文件。我遇到的问题是,文件会播放,但是如果它没有播放完你并且按下按钮,它就不会再响了。

XAML
<MediaElement x:Name="KickBasicAudio"
              Source="Assets/Drums/Dance/KickBasic.wav"
              AutoPlay="False" />
<Button Content="KICK" ClickMode="Press" Click="KickBasicPlay"/>

C#
private void KickBasicPlay(object sender, RoutedEventArgs e)
{
    KickBasicAudio.Play();
}

2 个答案:

答案 0 :(得分:1)

在这种情况下,也许SoundPlayer可能是更好的选择,因为这允许异步播放

using System.Media; //The reference needed.

private SoundPlayer _player = new SoundPlayer("file");

private void KickBasicPlay(object sender, RoutedEventArgs e)
{
    _player.Play();
}

答案 1 :(得分:0)

我认为您需要后台工作线程来执行此操作。试试这个。

using System.ComponentModel; //This is the reference needed.

private void KickBasicPlay(object sender, RoutedEventArgs e)
{
    BackgroundWorker thread = new BackgroundWorker();
    thread.DoWork += (sender, e) => { KickBasicAudio.Play() };
}