views:

13

answers:

1

Hello,

I'm trying to find out why the last commented command is necessary in order to play a sound:

private void Window_ContentRendered(object sender, EventArgs e)
{

  MediaElement MediaElement1 = new MediaElement();
  MediaElement1.Source = new Uri(@"My-absolute-path");
  //myGrid.Children.Add(MediaElement1);
}

Does anybody know? Thanks!

+1  A: 

If you don't want to add it to the visual tree, you probably want to use MediaPlayer instead of MediaElement.

private void Window_ContentRendered(object sender, EventArgs e)
{
    MediaPlayer MediaPlayer1 = new MediaPlayer();
    MediaPlayer1.Open(new Uri(@"My-absolute-path"));
    MediaPlayer1.Play();
}

See Multimedia Overview:

MediaElement is a UIElement that is supported by The Layout System and can be consumed as the content of many controls. It is also usable in Extensible Application Markup Language (XAML) as well as code. MediaPlayer, on the other hand, is designed for Drawing objects and lacks layout support. Media loaded using a MediaPlayer can only be presented using a VideoDrawing or by directly interacting with a DrawingContext. MediaPlayer cannot be used in XAML.

Quartermeister