How To Use Windows Media Player To Play Audio And Video
This how-to shows you how to use the Windows Media Player component in your C# project to play back various forms of audio and video. Please note that this control is only good for sustained sound or video - that is, media that lasts several seconds. For one-shot sound effects that need to be played back in rapid succession, the Windows Media Player control is not a good choice.
| Download: MediaPlayerTest.zip |
Unzip all files (executables plus dependencies) into a single folder
Adding WMP to the Toolbox
- Right click on the toolbox and select Add/Remove Items.
- Click on the Com Components tab. Scroll down to the bottom of the list and find Windows Media Player. Check the box beside it if it is not already checked.
- Click OK. The Windows Media Player component is now added on your toolbox.
Using WMP to Play a Media File
- Add the Windows Media Player control to your form and size appropriately. For sound applications, you may wish to set the Visible property to false - that way you don't have to worry about anyone fiddling with the playback controls. However, if you want users to be able to control the playback, leave the control visible.
- Set the URL to the path of the file on disk, or alternately, the URL of the file online. The file loads and automatically starts playing. Video shows up in the black region above the controls, and audio files show the Windows Media Player visualization.
- You can control playback by accessing the Ctlcontrols property, which contains the play(), pause(), stop() functions, to name a few. Other functions such as next() and previous() only work when a playlist is loaded.
- You can enabled and disable just the playback controls on the user interface by setting the Ctlenabled property.
Checking Playback Status
You can manually check the playback status of the Windows Media Player control by examining the playState property. To figure out which state it is in, use the WMPLib.WMPPlayState enumeration for comparisons. For example, the code below checks to see if a file is currently playing.
Detecting End of Playback
The Windows Media Player control throws an event when playback ends. If you wish to have files loop, you can simply use this event to call the player's Play method again.
- Click on the Media Player control in the Form Designer.
- In the Properties window, switch over to the Events listing.
- Double-click on the PlayStateChanged event to create a new event handler.
- Place the following code in the new Event Handler:
The code above checks to see if the state is now set to stopped. If so, we begin the media playing again, thus causing the file to loop indefinitely.