Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play mp3 files in C#?

Tags:

c#

mp3

I'm trying to play an MP3 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.

like image 247
Waffles Avatar asked Jun 27 '10 23:06

Waffles


2 Answers

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);
         isOpen = true;
      }

      public void Play(bool loop)
      {
         if(isOpen)
         {
            _command = "play MediaFile";
            if (loop)
             _command += " REPEAT";
            mciSendString(_command, null, 0, IntPtr.Zero);
         }
      }
}
like image 190
Joe Doyle Avatar answered Oct 07 '22 00:10

Joe Doyle


all you need to do is add a reference to the Window Media Player COM component. You need to add the reference to the file wmp.dll, which you can find in the System32 directory.

like image 42
Shaltiel Shmidman Avatar answered Oct 07 '22 02:10

Shaltiel Shmidman