msbg
msbg

Reputation: 4972

WindowsMediaPlayer (WMPLib) audio dies suddenly

I am trying to play audio in my winforms application. To do so, I use this:

           WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
           string path = "C:\\Windows\\Media\\Ring10.wav";
           wplayer.URL = path;
           wplayer.controls.play();

I use the WindowsMediaPlayer class because other classes will not play audio in the format that my audio file is in. The code above works until I add Process.GetProcesses(); or Process.GetProcessesByName... to a timer's tick event.

    private void timer1_Tick(object sender, EventArgs e)
    {
        Process[] processes = Process.GetProcesses();
    }

The first time the timer ticks and executes Process.GetProcesses();, the audio continues to play. However, the second time the timer ticks the audio is stopped. This happens if the timer is in the same form as the one playing the audio or in a different one. I have no idea why this would be happening. What is causing this issue?

Upvotes: 1

Views: 1263

Answers (1)

steve cook
steve cook

Reputation: 3224

Hold on...

       WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
       string path = "C:\\Windows\\Media\\Ring10.wav";
       wplayer.URL = path;
       wplayer.controls.play();

Are you keeping a reference to wplayer around somewhere? Like as a private field on your form?

If not, I think the garbage collector will randomly pick it up and kill it. It's probably just coincidence that getting a process list generates enough temporary garbage that the GC kicks in.

Try changing that to a

       private WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

[EDIT: If you have any more problems, try the minimal example below - this should work fine:

public partial class Form1 : Form
{
    Timer timer = new Timer();
    private WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

    public Form1()
    {
        InitializeComponent();

        string path = "C:\\Users\\Public\\Music\\Sample Music\\Kalimba.mp3";
        wplayer.URL = path;
        wplayer.controls.play();

        timer.Interval = 2000;
        timer.Tick += timer_Tick;
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        Process[] processes = Process.GetProcesses();
        Debug.WriteLine(processes.Length + " running processes");
    }


}

Upvotes: 4

Related Questions