Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 339
Yellow Avatar asked Oct 25 '13 13:10

Yellow


Video Answer


1 Answers

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();
like image 141
Jehof Avatar answered Oct 10 '22 03:10

Jehof