Sunday, March 30, 2008

WPF and Windows Media Player COM control

The WMPLib offers direct control to Windows Media Player to your C# applications. This provides a rich set of events and controls that is really useful if you would like to create a custom media player.

The code I wrote scans the computer (My Music) and builds up a library of artists, albums and songs using the directory structure. Any images found are used to create folder icons. I later found out that it is possible to access the Windows Media Player media collection library to access this information so next time I´ll probably use that) However, this requires the albums to be imported/added to the Windows Media Player.

There is a few neat trick available when using the WMP. One is that it sends events when ever the player state changes (see list of events). This enabled me to initiate a progress bar that displays the current position in the song (code 3) as well as skipping to the next song when a the current playing song was completed (code 8).

To add WMP in you code

Using WMPLib;

WindowsMediaPlayer _wmp;

public MyApp()
_wmp = new WindowsMediaPlayer();
// The event below tells WMP to call your own MediaProcess code
// when the WMP player changes state
_wmp.PlayStateChange += new _WMPOCXEvents_PlayStateChangeEventHandler(MediaProcessChange);

private void MediaProcessChange(int newState)
//The integer "newState" contains the state of the media player, ranging from 1 to 11
// see for mor infomation

// case 1: // Stopped
// case 2 : // Paused

case 3 : // Song starts playing

progress.Maximum = _wmp.currentMedia.duration;
progress.SetValue(ProgressBar.ValueProperty, _wmp.controls.currentPosition);

BackgroundWorker _worker = new BackgroundWorker();
_worker.WorkerReportsProgress = false;
_worker.WorkerSupportsCancellation = true;

_worker.DoWork += delegate(object s, DoWorkEventArgs args)
while (_wmp.controls.currentPosition <>
// Dispatcher to update the U.I progressbar every two seconds
Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { progress.SetValue(ProgressBar.ValueProperty, _wmp.controls.currentPosition); }, null);
}; // End delegate

// case 4 : // ScanFordward
// case 5 : // ScanBackwards
// case 6 : // Buffering
// case 7 : // Waiting

case 8: // Song ended, play next


// case 9 : // Transitioning
// case 10 : // Ready
// case 11 : // Reconnecting

The "progress" object is a XAML added obj of the type ProgressBar. These handy U.I elements can be set to the maximum value (instead of 1 to 100) The maximum value I set to the entire lenght of the song. This way the current position scale to the bar.

There is a good tutorial for making a media player at Pauls Blog. Additionally, another custom media player by Sacha Barber. The MSDN network has extensive API info as always (but perhaps in a really boring format)

No comments: