You are on page 1of 2

Using MCI for MP3 Playback C#

Using MCI for playing MP3 is very simple. I was so happy when I clicked the play button on my application and I did not get and Exception error. It took me 2min to code the class after looking at this & this. In my free time I will make a sexy UI and add some more functions but for now you could play you self.

private void button1_Click(object sender, System.EventArgs e) { // my error checking lol if(textBox1.Text.Length!=0) test.Open(textBox1.Text); } private void button2_Click(object sender, System.EventArgs e) { test.Play(true); } private void button3_Click(object sender, System.EventArgs e) { test.Close(); }

Class
To use the MCI Functions we have to import the winmm.dll.
[DllImport("winmm.dll")] private static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);

Then you go to the MSDN look up a command and its party time.

Code

public class Player { private string Pcommand; private bool isOpen; [DllImport("winmm.dll")] private static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback); public Player() { } public void Close() { Pcommand = "close MediaFile"; mciSendString(Pcommand, null, 0, IntPtr.Zero); isOpen=false; } public void Open(string sFileName) { Pcommand = "open \"" + sFileName + "\" type mpegvideo alias MediaFile"; mciSendString(Pcommand, null, 0, IntPtr.Zero); isOpen = true; } public void Play(bool loop) { if(isOpen) { Pcommand = "play MediaFile"; if (loop) Pcommand += " REPEAT"; mciSendString(Pcommand, null, 0, IntPtr.Zero); } } } If you have a question http://csharp-home.com/ nerdandy@gmail.com

You might also like