tags:

views:

115

answers:

4

I'm trying to play an MP# file in C# using this guide: http://www.crowsprogramming.com/archives/58

And I'm doing everything listed, but I still can't play any music in my C# program. Can anyone tell me what I'm doing wrong?

 static void Main(string[] args)
    {
        WMPLib.WindowsMediaPlayer a = new WMPLib.WindowsMediaPlayer();
        a.URL = "song.mp3";
        a.controls.play();
    }

The music file "Song" is in the bin folder.

A: 

There are a couple of things I would try:

1) Fully-qualify the path to that .mp3 file, just in case. 2) Try a.Ctlcontrols.play(); instead.

Also, I'm nearly certain that is a Windows (ActiveX control) that you are trying to load. It may need a windows context in order to load and work. I'm certain there is another way to play an .mp3, because I've used it before, but I couldn't find the code. It may have been part of the DirectX SDK though. Hope that helps.

Robert Seder
A: 

I haven't used the Windows Media Player COM object, but here's a link to an alternative method. (I am not the author.) It uses pinvoke to call winmm.dll to play the MP3. I tested it out on Windows Server 2008 and it worked just fine.

Here's a sample class using the code form the link.

using System.Runtime.InteropServices;

public class MP3Player
{
      private string _command;
      private bool isOpen;
      [DllImport("winmm.dll")]

      private static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);

      public void Close()
      {
         _command = "close MediaFile";
         mciSendString(_command, null, 0, IntPtr.Zero);
         isOpen = false;
      }

      public void Open(string sFileName)
      {
         _command = "open \"" + sFileName + "\" type mpegvideo alias MediaFile";
         mciSendString(_command, null, 0, IntPtr.Zero);  18.
         isOpen = true;
      }

      public void Play(bool loop)
      {
         if(isOpen)
         {
            _command = "play MediaFile";
            if (loop)
             _command += " REPEAT";
            mciSendString(_command, null, 0, IntPtr.Zero);
         }
      }
}
Joe Doyle
A: 

Hi Waffles,

I'm not sure it's still relevant but when I tried it, it only worked when the code ran not in the main thread, i.e., this.InvokeRequired == false

So, I would advice you try something like:

ThreadPool.QueueUserWorkItem(
             delegate(object param)
             {
                 WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer();
                 player .URL = "song.mp3";                     
             });

player.controls.play() is not needed since the player is set to auto play.

I'm not sure as to why the main thread won't play correctly but I hope this will help.

AlonEl