Wednesday, September 23, 2009

Programming with Windows Media Player and C#

I'm working on a prospective project that requires me to play mp3 files on our NetMachine kiosks. Under the old Windows system, one can play WAV files by calling some internal Windows functions. I've never tried playing mp3 or wma media files from an application so I did some research. While there are 3rd party libraries available, the best option seems to be to use the interfaces exposed by Windows Media Player (WMP). Since practically all Windows PC's come equipped with some version of WMP, it is fairly safe to assume that the components can be found in all these PC's.

Adding WMP to a C# application is very simpler. Just add a reference to the file wmp.dll in your Visual Studio project. Then from within your code, just create an instance; point to the source media file; and call play():

WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer();
player.URL = @"c:\My Music\somesong.wma";;

You can also track state changes (eg. from playing to stopped) and respond appropriately using the standard event-handling model of .NET.

player.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(player_PlayStateChange);

You can also access the playlists defined in WMP programmatically, and extract information about the media file (ex. the artist, song title, album title, etc.) through the IWMPMedia interface:

WMPLib.IWMPMedia objMedia = player.currentMedia;
listBox1.Items.Add(String.Format("[{0}] {1} by {2}",

There is a downloadable Windows Media Player SDK 10 at Microsoft. I'm not sure what more it adds to the components that are already built-in to Windows. I did not bother installing it anymore. I guess its just sample programs.

No comments: