WinRT(重新)使用c#.NET中的mediaElement播放声音

时间:2012-12-16 14:45:00

标签: c# .net audio windows-8 windows-runtime

我正在使用MediaElement类在按钮点击时播放简单的声音。这对我来说很好,除非我正在点击它。在第二次点击时,我希望旧声音停止播放并重新开始播放声音。但Stop方法不起作用:

    public static MediaElement SoundDelete;
    public static void PlaySoundCash()
    {
        if (SessionHelper.getConfig("SoundDelete") == "true")
        {
            System.Diagnostics.Debug.WriteLine(SoundDelete.Position.ToString());
            SoundDelete.Stop(); //dosn't work
            SoundDelete.Position = new System.TimeSpan(0,0,0,0,0); //dosn't work
            System.Diagnostics.Debug.WriteLine(SoundDelete.Position.ToString());
            SoundDelete.Play();
        }
    }

在控制台中,时间跨度从不为0.我怎样才能从头开始播放声音?

1 个答案:

答案 0 :(得分:1)

我遇到了完全相同的问题。事实证明,将MediaElement添加到Visual Tree将允许您使用此额外功能。

将我的MediaElements添加到我的基本网格的子项中解决了这些问题。

例如:

C#

public static MediaElement SoundDelete;

private void MediaInit()
{
    // ...
    // load your sound file into SoundDelete
    // ...
    BaseGrid.Children.Add(SoundDelete);
}
public static void PlaySoundCash()
{
    System.Diagnostics.Debug.WriteLine(SoundDelete.Position.ToString());
    SoundDelete.Stop();
    SoundDelete.Position = new System.TimeSpan.Zero;
    System.Diagnostics.Debug.WriteLine(SoundDelete.Position.ToString());
    SoundDelete.Play();
}

或在XAML中:

<Grid Name="BaseGrid">
    <MediaElement Name="SoundDelete" Source="path_to_your_sound_file.mp3" />
</Grid>