Playing an MP3 or WAV File in C#

Playing an audio file such as an MP3 or WAV is incredibly easy in C#. For WAV files you can use the SoundPlayer class found in the System.Media namespace. Playing an MP3 will require referencing the Windows Media Player COM component.

How to Play a WAV file

To play the WAV file simply create a new SoundPlayer object, set the SoundLocation property to the location of your WAV file, and then use the Play method to play it.

System.Media.SoundPlayer player = new System.Media.SoundPlayer();
 
player.SoundLocation = "My Wav File.wav";
player.Play();

How to Play an MP3 file

Playing an MP3 with C# is just as easy as playing a WAV except that it requires you to use the Window Media Player COM component. So first, add a reference to wmp.dll, which you can find in the System32 directory. Here is an example of how to play an MP3 file:

WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
 
wplayer.URL = "My MP3 file.mp3";
wplayer.controls.play();

So there you have it; a simple example of how to play an MP3 and WAV file using C#. I hope you find it useful. If you have any questions feel free to ask.

April 5, 2009   Posted in: C#

8 Responses

  1. Eliot Ball - April 16, 2009

    Thanks a lot, this is really helpful!

  2. Eliot Ball - April 16, 2009

    I’m gonna use this in an app! (sorry for double post)

  3. Christina - June 9, 2009

    Hello…. thank you so much for posting this. This was very helpful. I am actually developing a website which should play mp3 files from a list of files and I had a hard time figuring it out. You made work so much easier….

  4. Guinness - June 10, 2009

    Hi,

    I’ve tried to get this working, but I can’t get the system.media to be acceble for me

  5. mudassir - January 13, 2010

    I am actually developing a Application in which should play mp3 files from a list of files when user touches picturesBox and I had a hard time figuring it out. You made work so much easier…. if you share some code
    please reply.. I wait.

  6. Henry Tang - February 11, 2010

    Very helpful.Thx

  7. charlie - May 5, 2010

    Hi, I saw your code, Im trying to make this a push button effect, when you press a button, it will play “the” wave file, but when I implemented there is always an error when I run the code, it says “FileNotFoundException was unhandled”

  8. rehu - July 2, 2010

    i am trying to do the coding above but i am getting the error
    Sound API only supports playing PCM wave files.
    pleae help

Leave a Reply