Does a MediaElement only play when it is embedded in XAML code?

*爱你&永不变心* 提交于 2019-12-10 14:44:29

问题


I have a sound player class that doesn't have any visuals at all, and I am trying to use a MediaElement to play my sounds. In all the test projects, in which the MediaElement is embedded in the XAML code, it works fine. However, in my code-only version, is doesn't play anything at all, even though the file has been loaded perfectly (I could see in the Debugger). I am doing the following:

public class MySoundPlayer
{
    private MediaElement player = new MediaElement();

    public MySoundPlayer()
    {
        player.LoadedBehavior = MediaState.Manual;
        player.UnloadedBehavior = MediaState.Stop;
        player.Volume = 1.0;
        player.MediaEnded  += player_MediaEnded;
        player.MediaOpened += playerr_MediaOpened;
        player.MediaFailed += player_MediaFailed;
    }

    private void player_MediaEnded(object sender, EventArgs e)
    {
        player.Stop();
        Debug.WriteLine("Stopped");
     }

    private void player_MediaOpened(object sender, EventArgs e)
    {
        Debug.WriteLine("Opened");
    }

    private void player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
    {
        Debug.WriteLine("Failed");
    }

    public void PlayFile(string fileName, bool loop)
    {
        player.Source = new Uri(fileName, UriKind.RelativeOrAbsolute);
        player.Play();
        player.Volume = 1.0;
    }
}

I double-checked if the file exist, which it does (and it is even loaded correctly), and that my sound is turned on. :-) Also, when I change the MediaElement by SoundPlayer, it works perfectly fine. The only difference I can find is that I do not have it embedded in the XAML code. Is this a requirement?


回答1:


In order to work the MediaElement must be part of the logical tree of your application and therefore must be added to some container (Grid, StackPanel) in your application.

You can add the MediaElement via XAML (as you have done it before) or you can add it during runtime via

LayoutRoot.Children.Add(player);

Instead of using the MediaElement you should use the MediaPlayer class. This will work (at least for me) without attaching it to XAML.

MediaPlayer player = new MediaPlayer();
player.Open(new Uri(fileName, UriKind.RelativeOrAbsolute));
player.Play();


来源:https://stackoverflow.com/questions/19591131/does-a-mediaelement-only-play-when-it-is-embedded-in-xaml-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!