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?
LayoutRoot
. Do I have to extend aUserControl
in order to use theMediaElement
? – Exigible