Tronald
Tronald

Reputation: 1585

Why does MediaPlayer silently fail if started before rendering has occurred?

I found this odd behavior with MediaPlayer by accident while helping someone with a problem and I want to see if any WPF guru's can explain it. I understand the below example is not practical, but it best demonstrates the behavior.

Lets say I throw a MediaPlayer in the MainWindow constructor and try to start it.

public MainWindow()
{
    InitializeComponent();
    MediaPlayer mp = new MediaPlayer();
    mp.Open(new Uri("Be Free.mp3", UriKind.Relative));
    mp.Play();
}

The MediaPlayer will silently fail and you will hear no music play. Now here is where things get interesting. Let's say we throw an OpenFileDialog in there before we start playing.

public MainWindow()
{
        InitializeComponent();
        MediaPlayer mp = new MediaPlayer();
        mp.Open(new Uri("Be Free.mp3", UriKind.Relative));

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.ShowDialog();

        mp.Play();
}

The music will begin to play with no problem. You don't even have to select a file, you can just Cancel the Dialog and it will work.

For reference, I am Microsoft.Win32.OpenFileDialog. Can anyone explain how activation of this allows the MediaPlayer to work?

Upvotes: 1

Views: 67

Answers (1)

Nico
Nico

Reputation: 12683

I would expect this would have to do with the GC cleaning up your instance of MediaPlayer as it is defined within the constructor.

As a test I built a small example and subclassed the MediaPlayer as such and break point on the finalizer. Sure enough the finalizer was called shortly after my window appeared.

public class MyMediaPlayer : MediaPlayer
{

    ~MyMediaPlayer()
    {

    }
}

This was tested with a similar call in my window constructor.

public MainWindow()
{
    InitializeComponent();
    MyMediaPlayer _mp;
    _mp = new MyMediaPlayer();
    _mp.Open(new Uri("song.m4a", UriKind.Relative));
    _mp.Play();
}

Now if when i made _mp an instance level object such as.

MyMediaPlayer _mp;
public MainWindow()
{
    InitializeComponent();
    _mp = new MyMediaPlayer();
    _mp.Open(new Uri("song.m4a", UriKind.Relative));
    _mp.Play();
}

I no longer experienced this issue and the finalizer was only hit when appropriate (ie closing the window).

note the subclass is not required and only used for finalizer illustrations

Upvotes: 2

Related Questions