Click here to Skip to main content
14,551,019 members

PVS.MediaPlayer - Audio and Video Player Library

Rate this:
4.94 (171 votes)
Please Sign up or sign in to vote.
4.94 (171 votes)
8 May 2020CPOL
Microsoft Media Foundation based easy-to-use library with many added features
This article contains a short guide for using the PVS.MediaPlayer library in your applications. PVS.MediaPlayer is an easy-to-use, small and powerful library for playing media files, webcams and audio devices using Microsoft Media Foundation. The accompanying example programs show more possibilities of the library that are not covered in the article.

Version 0.99, recommended update: fixed live streams (eg internet radio), play images as video, seamless video image transitions, mp4 chapters, full all-screens display modes and others. See the 'About PVS.Media Player version.txt' download file for more information.

Library size: 240 KB
Platform: Microsoft Windows 7 or higher - WinForms Any CPU
Requirements: Microsoft .NET Framework 2.0 or higher
License: The Code Project Open License (CPOL)

PVS.MediaPlayer has built in (part of) the Media Foundation .NET library by nowinskie and snarfle ( Licensed under either Lesser General Public License v2.1 or BSD. See license.txt or BSDL.txt for details (

PVS.MediaPlayer (Media Foundation) plays these audio and video formats: .3g2, .3gp, .3gp2, .3gpp, .aac, .adts, .asf, .avi, .m4a, .m4v, (some) .mkv, .mov, .mp3, .mp4, .mpeg, .mpg, .sami, .smi, .wav, (some) .webm, .wma and .wmv (and maybe others) and these image formats (played as video): .bmp, .gif, .ico, .jfif, .jpeg, .jpg, .png, .tif and .tiff (and maybe others). PVS.MediaPlayer can play media files with a missing or incorrect file extension, provided the actual format can be played by Media Foundation.

Version 0.99, Copyright © 2020 PVS The Netherlands

Image 1


PVS.MediaPlayer is an easy-to-use media player library for playing media files in .NET Framework WinForms applications using Microsoft Media Foundation, Media Foundation .NET and other technologies, with:

  • high quality audio and video
  • built-in audio and video codecs
  • integrated webcam player
  • display overlays, shapes and clones
  • multiple full screen display modes
  • video tracks info and selection
  • video preset and custom sizes
  • audio tracks info and selection
  • audio standard volume and balance control, or
  • audio up to 16 channels separate volume control
  • audio devices manager, info and selection
  • trackbar managers (position, audio and others)
  • media info (tags) with album art
  • media subtitles (srt)
  • and more
  • The sample applications are compiled using Microsoft .NET Framework 4.0.
  • PVS.MediaPlayer and the sample applications do not contain viruses, spyware, advertisements or other malware, do not collect information, do not change anything permanently on your computer and do not connect to the internet.

Please note that a VB.NET version of the article can be downloaded from the link at the top of this article.

Image 2

Image 3

Brief Instructions on How to Use PVS.MediaPlayer


  1. Adding PVS.MediaPlayer to your Application
  2. Check if Media Foundation is Installed
  3. Creating a Player
  4. Error Handling
  5. Player Events
  6. Player Display
  7. Full Screen Display
  8. Display Overlays
  9. Display Clones
  10. Playing a Media File
  11. Audio Settings
  12. Video Settings
  13. Trackbars
  14. Webcams
  15. Playing Audio Input Devices
  16. Keeping Track Of Your Devices
  17. Playing Images
  18. Losing the Gap
  19. From Here On...

Due to the large number of functions of the PVS.MediaPlayer library, not all options can be described here. See the sample applications for more information.

This article assumes that you use Microsoft Visual Studio for software development.

1. Adding PVS.MediaPlayer to your Application

You can use the PVS.MediaPlayer library in your applications by adding a reference to the "PVS.MediaPlayer.dll" file to an application's project:

First download "" from the link at the top of this article and extract the library wherever you want on your hard drive. The .xml file contains information for IntelliSense from Visual Studio and is not needed with your finished application.

Next, open your application's project in Visual Studio (or create a new project) and add a reference to the library. You can do this by right-clicking on the project in solution explorer (or using the Project menu) and then select "Add Reference": choose the "Browse" option and locate and select "PVS.MediaPlayer.dll". Now you're ready to use PVS.MediaPlayer.

Finally, to use shorter names in the Visual Studio editor, type at the top of each project file that uses the library:

using PVS.MediaPlayer;

Before creating one or more PVS.MediaPlayer players, ensure that Media Foundation is installed (see also 2. Check if Media Foundation is Installed). But once you've done that and it's installed, here's a simple way to play a movie in a control (in this case, "panel1") in your application:

Player myPlayer = new Player();
myPlayer.Play(@"C:\Videos\MyMovie.mp4", panel1);

To stop playing and remove myPlayer, use:

myPlayer = null;

You should always remove all players by using their Dispose method before your application ends.

2. Check if Media Foundation is Installed

The PVS.MediaPlayer library can only be used on computers with Microsoft Media Foundation installed.

You can check whether Media Foundation is installed on a computer using the (static) Player.MFPresent property. This property returns 'true' if Media Foundation is installed, for example:

if (!Player.MFPresent) MessageBox.Show("MediaFoundation is not installed.");

If you try to create a player on a computer without Media Foundation, an exception (error) is thrown and the player is not created.

The PVS.MediaPlayer library also requires the presence of Microsoft Windows 7 or higher. The MFPresent property also checks for this and returns 'false' if not present.

The text and code samples in this article assume that Windows 7 or higher is used and that Media Foundation is installed.

Note: A static method or property can be used without creating a player. Another example of a static property in the PVS.MediaPlayer library is to get the library version number, for example:

label1.Text = Player.VersionString;

3. Creating a Player

If you want to play a media file, you must first create a player. In your application, you can create as many players as you want and also remove them if you no longer need them. You can use them at the same time, even to play the same media file.

Once you have created a player, you can continue to use it to play media files. You do not have to stop a playing media file to play another media file, the player will take care of it.

In the following example, the player's name is "myPlayer" and some lines of code are added to use one of the events raised by the player.

A player can inform you about changes in the playback status by sending you 'event messages'. You can 'catch' these events with your player's event handler and act accordingly. For example, in the case of a MediaEnded event (that tells you that a media file has finished playing), you may want to play another (next) media file (see also 5. Player Events).

Adding a Player with event handler to a new Windows Forms application:

using PVS.MediaPlayer;

namespace MyApplication
    public partial class Form1 : Form
        Player myPlayer;

        public Form1()

            myPlayer = new Player();
            myPlayer.Events.MediaEnded += MyPlayer_MediaEnded;

        void MyPlayer_MediaEnded(object sender, EndedEventArgs e)
            switch (e.StopReason)
                case StopReason.Finished:
                    // media has finished playing

                case StopReason.AutoStop:
                    // media is stopped by the player to play next media

                case StopReason.UserStop:
                    // media is stopped with the Player.Stop method

                case StopReason.Error:
                    // media has stopped because an error has occurred

Now all you have to do is tell the player which media file (path and file name) to play and, if it is a movie, where to display it (player display).

4. Error Handling

Every method and every property of a PVS.MediaPlayer player returns a result (error) code. The result can be obtained through the LastError property of a player (and sometimes from a method itself). You should always check if a method or property works as you expect by checking the LastError property that returns a Boolean value, for example:

myPlayer.Audio.Volume = 2f; // value out of range (0.0 - 1.0)
if (myPlayer.LastError) MessageBox.Show(myPlayer.LastErrorString);

The LastErrorString property of a player returns a description of the last error that occurred and the LastErrorCode property returns the error code (0 = no error).

A PVS.MediaPlayer player does not throw or pass on exceptions, so you don't have to use the try-catch construction with the player's instructions.

However, an exception is thrown when creating a player while Media Foundation is not installed on the system or with an unsupported version of Windows (see also 2. Check if Media Foundation is Installed).

5. Player Events

The events raised by PVS.MediaPlayer allow your application to react to certain changes in the state of your player, like when a mediafile has finished playing. You don't have to use any of the events, and if you don't, PVS.MediaPlayer will ignore them too and not send any event messages to your application.

Some player functions can only be activated by subscribing to a player event, such as obtaining audio peak levels or subtitles. Other events can be very useful for updating interface items in different locations (for example, the playback position or audio volume) or checking whether a setting has really changed (for example, when selecting another audio device).

The MediaPositionChanged event differs slightly from the others because it is sent very often when a media file is being played. It provides information about the player's playback position and you can use it to update a number of position indicators on the screen, such as a slider (if you are not using the player's position slider) and / or some 'counters', for example:

private void MyPlayer_MediaPositionChanged(object sender, PositionChangedEventArgs e)
    TimeSpan fromStart = TimeSpan.FromTicks(e.FromStart);
    TimeSpan toStop = TimeSpan.FromTicks(e.ToStop);

    myTrackBar.Value = fromStart.TotalMilliseconds;

    label1.Text = fromStart.ToString(@"hh\:mm\:ss")
    label2.Text = toStop.ToString(@"hh\:mm\:ss")

Other events that may be sent very often are the MediaPeakLevelChanged and the MediaSubtitleChanged events. Because these events are sent so often, the event handlers should handle the events quickly and efficiently to prevent the application from being delayed.

By using the myPlayer.TimerInterval property, you can change the frequency by which the MediaPositionChanged and MediaPeakLevelChanged events are sent (default 100 milliseconds), for example:

myPlayer.TimerInterval = 50;

This timer also controls the updates of the (both optional) player's position slider and taskbar progress indicator.

Image 4

6. Player Display

To view the video images of media files, your player must have a display. You can use any WinForms control (including a form) as a player display, but a panel would be a good choice because it has the least resources attached and is well suited for that. You can specify the player's display when you create a player or at any other time, even when media is being played. The player remembers which display to use, so you don't have to repeat the setting every time (this is the case with all player settings).

Player myPlayer = new Player(panel1);
myPlayer.Display.Window = panel2;
myPlayer.Play(myVideo, this);

The display of a player can be treated as a 'normal' WinForms control, you can add other controls to it and adjust its properties to your needs. To easily add items to a player's display, with transparency and opacity options, you can use a PVS.MediaPlayer display overlay (see 7. Display Overlays).

You can change the way video images are shown on the player's display in many different ways, for example:

// use one of the preset formats (default: DisplayMode.ZoomCenter):
myPlayer.Display.Mode = DisplayMode.Stretch;

// use a custom format (default: DisplayMode.ZoomCenter):
myPlayer.Video.Bounds = new Rectangle(10, 20, 300, 400);

// use a display shape (default: DisplayShape.Normal):
myPlayer.Display.Shape = DisplayShape.Oval;

A player also offers multiple options to copy the contents of its display (without copying any overlapping windows), for example:


You can use the same display for multiple players if you organize the position of the video with the Player.Video.Bounds property and you can play videos without using a display to hear only the video sound.

7. Full Screen Display

If you want to display a player's display on the entire computer screen, you can use the player's full screen option, for example:

myPlayer.FullScreen = true;

Before (or after) doing this, you can use the player's FullScreenMode option to select what is displayed on the full screen:

  1. FullScreenMode.Form - shows the form (the player's display is on) full screen
  2. FullScreenMode.Parent - shows the parent control (the player's display is in) full screen
  3. FullScreenMode.Display - shows the display of the player in full screen (default setting)
myPlayer.FullScreenMode = FullScreenMode.Form;

The player's display or its parent can't be inside any other control than the form itself if you want to use mode 2 or 3.

With each full screen display mode, the player's display always remains part of the form on which it is placed (there is no special or separate full screen window).

Each player can have a full screen display as long as its display is not on a form that already has a full screen display of another player.

8. Display Overlays

With a PVS.MediaPlayer display overlay, you can very easily display something (like text, pictures and movies) on top of a movie. A PVS.MediaPlayer display overlay is a form, just like the ones you use in your .NET Windows Forms Application projects. PVS.MediaPlayer just displays it on top of a player's display.

To create a display overlay, just create a new form ("Form2" in this example) and add all desired items, for example, an image logo and some lines of code, and add it to the player as follows:

Form2 myOverlay = new Form2();        // create an instance of Form2
myPlayer.Overlay.Window = myOverlay;  // and attach it to the player

To remove a display overlay from the player, set the overlay window to another overlay or to null:

myPlayer.Overlay.Window = null;

A display overlay can be the same size as the player's display or the same size as the video image of the playing media, for example:

myPlayer.Overlay.Mode = OverlayMode.Display;  // the default value is OverlayMode.Video

A central point in a display overlay code is the form's VisibleChanged event. This event indicates when a display overlay is activated or deactivated. You can switch the various used items in the display overlay code, for example a timer, on or off accordingly.

See the example applications "How To ..." for a more detailed description of and various tips for using display overlays.

9. Display Clones

If you want your player to have multiple displays that all show the same image (for example, for use on multiple monitors), you can use one or more PVS.MediaPlayer display clones. A display clone is a copy of the main display including all items that you have added to it and (optionally) its display overlay. Each display clone can have its own independent size and has different adjustable features. You can add a display clone to a player with, for example:


Changing the properties of a display clone differs slightly from the standard methods. You must specify a data structure named CloneProperties to change one or more properties of a display clone. You can change an existing CloneProperties structure or create a new one, for example:

CloneProperties properties = myPlayer.DisplayClones.GetProperties(panel4);
properties.DragEnabled = true;
properties.Shape = DisplayShape.Oval;
myPlayer.DisplayClones.SetProperties(panel4, properties);

You can also use the CloneProperties structure to set the properties of all existing display clones at once.

Image 5

10. Playing a Media File

To play a media file, you can use one of the player's Play methods. With the Play methods, you can also specify the start and end time of the media and whether the media should be repeated when playback has finished.

To create a (tiny) mediaplayer, add a button ("button1") and a panel ("panel1") to your form and add the PlayMedia method (see below) to the code (for a 'standard display look', you can set the background color of the panel to black). Double-click the button on your form and add the PlayMedia instruction in the automatically created buttonclick handler. The project code now looks something like this:

using PVS.MediaPlayer;

namespace MyProject
    public partial class Form1 : Form
        Player myPlayer;
        // Form2 myOverlay; // create a display overlay (Form2)
                            // with the Visual Studio designer
        // Form myDisplayClone;
        OpenFileDialog myOpenFileDialog;
        string[] myMovies;
        int movieToPlay = 0;
        Point buttonLocation;

        public Form1()

            myPlayer = new Player();
            myPlayer.Events.MediaEnded += MyPlayer_MediaEnded;

            myPlayer.Display.Window = panel1;
            myPlayer.Display.Mode = DisplayMode.Stretch;

            myPlayer.Display.DragEnabled = true;

            // myOverlay = new Form2();
            // myPlayer.Overlay.Window = myOverlay;

            // myDisplayClone = new Form();
            // myDisplayClone.BackColor = Color.Black;
            // myDisplayClone.Show();
            // myPlayer.DisplayClones.Add(myDisplayClone);

            myOpenFileDialog = new OpenFileDialog();
            myOpenFileDialog.Multiselect = true;

            this.KeyPreview = true;
            this.KeyDown += new KeyEventHandler(Form1_KeyDown);

        void MyPlayer_MediaEnded(object sender, EndedEventArgs e)
            if (e.StopReason == StopReason.Finished) PlayNextMedia();

        private void PlayMedia(string fileName)

            if (myPlayer.LastError)
                MessageBox.Show(fileName + "\r\n\r\n" + myPlayer.LastErrorString);
                if (myMovies.Length > 1) PlayNextMedia();

        private void button1_Click(object sender, EventArgs e)
            if (myOpenFileDialog.ShowDialog(this) == DialogResult.OK)
                myMovies = myOpenFileDialog.FileNames;
                movieToPlay = 0;

        private void PlayNextMedia()
            if (++movieToPlay >= myMovies.Length) movieToPlay = 0;

        private void Form1_KeyDown(object sender, KeyEventArgs e)
            if (e.KeyCode == Keys.Space)
                e.Handled = true;

        private void ToggleFullScreen()
            if (myPlayer.FullScreen)
                myPlayer.FullScreen = false;
                button1.Location = buttonLocation;
                buttonLocation = button1.Location;
                myPlayer.FullScreen = true;
                button1.Location = new Point(24, 24);

This basic example can easily be expanded with other desired functionality, such as a position slider, a pause and stop button or changing the audio output device. See the text below and the example application "How To ..." how you can do that and for more examples.

Image 6

11. Audio Settings

A media file can contain multiple audio tracks (streams) and each track can have multiple channels. Multiple tracks are used to provide alternative audio for the media, for example, a commentary track or different languages. The channels in a track contain the audio information and usually, there are 2 channels for stereo output, but there may also be less or more for surround sound, for example.

The media starts playing the standard selected tracks, but these can easily be changed. For example, you can display the tracks in a menu and let the user select one of the tracks.

Information about the available audio tracks in the media being played can be obtained with:

int count = myPlayer.Media.AudioTrackCount; // get the number of audio tracks
AudioTrack[] tracks = myPlayer.Media.GetAudioTracks(); // get information about each track

// the information can be used to display some properties of the tracks,
// for example in a menu:
myMenu.Items.Add(tracks[0].Name + " " + tracks[0].Language); // and for all other tracks

To select one of the audio tracks in the playing media use, for example:

myPlayer.Audio.Track = 1; // select the second audio track

You can change the audio volume and balance settings of the selected track with, for example:

myPlayer.Audio.Volume = 0.5f;  // values from 0.0 to 1.0
myPlayer.Audio.Balance = 0.1f; // values from -1.0 to 1.0

or you can change the volume of each individual channel (values from 0.0 to 1.0, up to 16 channels) with, for example:

// get the audio volumes for each channel with:
float[] channelVolumes = myPlayer.Audio.ChannelVolumes;

// to change the volume of, for example, the right (or 2nd) channel, use:
channelVolumes[1] = 0.5f;
myPlayer.Audio.ChannelVolumes = channelVolumes;

and of course, you can temporarily mute the audio (while maintaining the volume settings), for example:

myPlayer.Mute = true;

The volume, balance, or channel volume (and the following audio device) settings are player settings, which means that they will be used for all subsequent media until they are changed again.

By default, a PVS.MediaPlayer player uses the system's default audio output device (if any), but this can be changed using the Player.Audio.Device property. This property uses an AudioDevice data structure.

The AudioDevice data structures of the system's enabled audio devices can be retrieved with:

AudioDevice[] devices = myPlayer.Audio.GetDevices();
// the information can be used to display some properties of the devices,
// for example in a menu:
myMenu.Items.Add(devices[0].Name); // and for all other devices

To select one of the devices retrieved from GetDevices (usually selected from a menu), use:

myPlayer.Audio.Device = devices[index]; // where index represents a device in the list

A player also offers direct access to the system's audio control panels:


Please refer to the sample applications "How To ..." for more information about the audio options and settings of the PVS.MediaPlayer library.

12. Video Settings

Just as with audio tracks, a media file can also contain multiple video tracks (streams). The media starts playing the standard selected track, but it can easily be changed. For example, you can display the names of the video tracks in a menu and let the user select one of the tracks.

Information about the available video tracks in the media being played can be obtained with:

int count = myPlayer.Media.VideoTrackCount;            // get the number of video tracks
VideoTrack[] tracks = myPlayer.Media.GetVideoTracks(); // get information about each track

// the information can be used to display some properties of the tracks,
// for example in a menu:
myMenu.Items.Add(tracks[0].Name + " " + tracks[0].Language); // and for all other tracks

To select one of the video tracks in the playing media use, for example:

myPlayer.Video.Track = 1; // select the second video track

The video image of a media file can be displayed in any desired size and there are various options, such as adjusting the brightness, to change the video image, for example:

myPlayer.Display.Mode = DisplayMode.Stretch;
myPlayer.Video.Bounds = new Rectangle (10, 20, 300, 400);
myPlayer.Video.Brightness = 0.5;

A player also offers direct access to the system's display control panel:


See the sample applications "How To ..." for more information about the video options and settings of the PVS.MediaPlayer library.

13. TrackBars

You may want to use a trackbar type control with your player to show and change the playback position of a mediafile. That's not a difficult task, although there's more to it than just might seem at first sight. That's why PVS.MediaPlayer can handle this kind of control for you.

Just add a TrackBar control to your form (or display overlay) and tell the player to handle it with:

myPlayer.Sliders.Position.TrackBar = trackBar1;

By setting the myPlayer.Sliders.Position.Mode option, you can have the trackbar show the position between the beginning and end of a mediafile (PositionSliderMode.Track) or between the player's media start- and end time (PositionSliderMode.Progress). The position slider offers various other options.

Similarly, you can also let the player handle an audio volume slider (myPlayer.Sliders.AudioVolume), an audio balance slider (myPlayer.Sliders.AudioBalance), a playback speed slider (myPlayer.Sliders.Speed) and/or a playback shuttle slider (myPlayer.Sliders.Shuttle):

myPlayer.Sliders.AudioVolume = trackBar2;

The sliders controlled by the player are only for input by the user. The values of the sliders should not be set from code. Use the corresponding properties (for example, myPlayer.Audio.Volume = 0.5f) to (also) change the sliders.

14. Webcams

A PVS.MediaPlayer player can 'play' webcams (without sound) in the same way as media (video) files. Of course, there are a few things missing when playing a webcam, for example, no media duration is known and there is no adjustable playback position or speed. But you have for example the same video options as with media files, such as the many display options, overlays, clones, and high-speed video image copy.

A webcam can be played by using the Player.Play method where the webcam to be played is specified: You can get information about the webcams available on the system with the Player.Webcam.GetDevices method, for example:

WebcamDevice[] webcams = myPlayer.Webcam.GetDevices();
// the information can be used to display the names of the webcams,
// for example in a menu:
myMenu.Items.Add(webcams[0].Name); // and for all other webcams

The Player.Webcam.GetDevices method returns null if no webcams are available. To play one of the webcams retrieved from the GetDevices method (usually selected from a menu), use for example:

myPlayer.Play(webcams[0], panel1);

If the player has already been assigned a display window, the "panel1" parameter can be omitted as usual. Use a player's LastError property in the same way as with media files to detect errors with webcam instructions (see 4. Error Handling).


PVS.MediaPlayer provides easy access to the following properties of a webcam: BacklightCompensation, Brightness, ColorEnable, Contrast, Exposure, Flash, Focus, Gain, Gamma, Hue, Iris, Pan, Roll, Saturation, Sharpness, Tilt, WhiteBalance and Zoom (and maybe others).

To get information about a property of the active webcam use for example:

WebcamProperty focus = myPlayer.Webcam.Focus;
if (myPlayer.LastError) MessageBox.Show("Webcam focus not available.");

A webcam may not support all properties. You can check whether a property is supported by a webcam with (instead of using the LastError property as above), for example:

if (focus.Supported) Messagebox.Show("The webcam's focus is adjustable.");

If the property is supported by a webcam, the property has a minimum and maximum (or on/off) value that can be obtained with, for example:

MessageBox.Show("The webcam's focus minimum value = " + focus.Minimum);

Use the 'Value' setting to change the value of a webcam property, for example:

focus.Value = 50;
myPlayer.Webcam.Focus = focus;

Please note that for example 'myPlayer.Webcam.Focus.Value = 50;' does not set the value on the webcam.

Some properties can be automatically adjusted by a webcam if necessary. You can check whether this option is supported for a property with, for example:

if (focus.AutoSupported) MessageBox.Show("The webcam supports automatic focus.")

And you can check whether the automatic control setting of the property is activated with, for example:

if (focus.AutoEnabled) MessageBox.Show("The webcam's focus is adjusted automatically.")

The automatic control setting (if supported) of a property can be changed with for example:

focus.AutoEnabled = true;
myPlayer.Webcam.Focus = focus;

When you set the value of a webcam's property, the webcam's automatic control of the property is disabled.


A webcam might be able to output video in several different formats. A format includes a size (width and height) of the video frames and a frame rate. The video output format of a webcam can be set with the Player.Play methods for webcams:

You can get a list of the available video output formats of a webcam with, for example:

WebcamDevice[] webcams = myPlayer.Webcam.GetDevices(); // see above
WebcamFormat[] formats = myPlayer.Webcam.GetFormats(webcams[0]);

Because a webcam can easily contain more than 100 different formats, you can make a preselection with the GetFormats method, for example, to only get formats with a frame rate of 30 frames or more per second, use:

WebcamFormat[] formats = myPlayer.Webcam.GetFormats(false, -1, -1, 30);
// the information can be used to display the formats,
// for example in a menu or a ListBox control:
StringBuilder text = new StringBuilder(32);
for (int i = 0; i < formats.Length; i++)
    text.Append(formats[i].Width).Append(" x ").Append(formats[i].Height)
    .Append(", ").Append(formats[i].FrameRate).Append(" fps");
    text.Length = 0;

To play a webcam with a specific video format, use one of the Player.Play methods with the desired video output format as a parameter, for example:

myPlayer.Play(webcams[0], formats[10]);

The player can also choose one of the available formats for you by using the quality option, for example:

myPlayer.Play(webcams[0], WebcamQuality.High);

If you do not specify a format, the player uses the default format of a webcam. Here is a complete example for playing a webcam:

WebcamDevice[] webcams = myPlayer.Webcam.GetDevices();
if (webcams == null) MessageBox.Show("No webcams found.");
    if (myPlayer.LastError) MessageBox.Show(myPlayer.LastErrorString);

You cannot use a webcam (a Player.LastError will be reported) if it is being used by another application, if its use is blocked by the Windows privacy settings or if it is not properly connected to the computer. If a webcam is disconnected during playback, playback is stopped and the player's MediaEnded event is raised with e.StopReason = Error, an error code (e.ErrorCode) and a value indicating that a webcam was playing (e.Webcam).

Notes: When using .NET Framework version 3.5 or lower, no more than one webcam is listed with the Player.Webcam.GetDevices method. The parameters of the webcam methods used here are described with Visual Studio intellisense. A PVS.MediaPlayer player cannot record video from a webcam. Starting and stopping a webcam usually takes more time than starting and stopping media files (maybe use 'async/await' or similar with slow starting webcams).

The PVS.MediaPlayer webcam options have only been tested with USB-connected webcams.


Audio (for example, microphone output) can be added to the video of a webcam by specifying an audio input device with the Player.Play method:

You can get a list of audio input devices with the Player.AudioInput.GetDevices method, for example:

AudioInputDevice[] microphones = myPlayer.AudioInput.GetDevices();
// the information can be used to display the names of the webcams,
// for example in a menu:
myMenu.Items.Add(microphones[0].Name + " " + microphones[0].Adapter); // for all devices

The word 'microphones' is used here, but any device that supplies audio input to the computer can be used.

The Player.AudioInput.GetDevices method returns null if no devices are available. To add one of the devices from the GetDevices method (usually selected from a menu) to a webcam video use for example:

WebcamDevice[] webcams = myPlayer.Webcam.GetDevices();
AudioInputDevice[] microphones = myPlayer.AudioInput.GetDevices();
myPlayer.Play(webcams[0], microphones[0], panel1);

If the player has already been assigned a display window, the "panel1" parameter can be omitted as usual. Use a player's LastError property in the same way as with media files to detect errors with webcam instructions (see 4. Error Handling).

If you are already playing a webcam, you can also add or change an audio input device with, for example:

myPlayer.Webcam.AudioInput = microphones[0];

The player raises the "MediaAudioInputDeviceChanged" event (if subscribed to) when the audio input device of a webcam has changed. Note: If the audio output of a player is set to a type of speakers, audio feedback may occur if a microphone is used.


When a webcam video is combined with audio input (Media Foundation aggregated source), a serious delay may occur during playback. This is probably caused by the audio input, which also slows down video playback. This has only been tested on a very limited number of computers and may not occur on all computers. More tests will have to be done.

If unwanted delays occur while playing a webcam with an audio input device, you can use another simple method where 2 players are used simultaneously. This method is described below (see 15. Playing Audio Input Devices).

15. Playing Audio Input Devices

Audio input devices connected to the computer can also be 'played' on their own with the Player.Play method, for example:

AudioInputDevice[] microphones = myPlayer.AudioInput.GetDevices(); // see above

The word 'microphones' is used here, but any device that supplies audio input to the computer can be used.

With this option you can also play the sound of a microphone and the video of a webcam on 2 separate players to prevent delays (see above 14. Webcams), for example:

WebcamDevice[] webcams = myPlayer.Webcam.GetDevices();
AudioInputDevice[] microphones = myPlayer.AudioInput.GetDevices();

If desired, an additional 'anti-delay' option can also be set on the audio player, for example: myPlayer2.LowLatency = true; When using this method, every time the webcam player has been changed (for example, when a different format is selected), the audio player must also be restarted (with the Player.Play method). But again, it is not known whether these delays occur on all computers.

This may require a little extra management, but it is easy enough to apply as a temporary solution to the delay problem when playing multiple sources simultaneously.

The PVSPlayerExample application uses this method.

Note: If the audio output of a player is set to a type of speakers, audio feedback may occur if a microphone is used.

16. Keeping Track Of Your Devices

To track system changes to the devices that your player uses, a PVS.MediaPlayer player offers the following options:

Webcams (video devices)

When a used webcam is disabled or removed, the player stops playing and raises the "MediaEnded/Notice" events (when subscribed to) with e.StopReason == StopReason.Error. To keep your webcam selection menu up-to-date, rebuild the menu with the available webcams (Player.Webcam.GetDevices) when the menu is opening.

Audio Output Devices (e.g. speakers and headphones)

When the audio output devices of the system are changed, the player makes any necessary changes (such as switching to the default audio output device and adjusting peak level information) and raises the "MediaSystemAudioDevicesChanged" (when subscribed to). You can use the "MediaSystemAudioDevicesChanged" event to, for example, customize menus, notify the user and prevent a removed device from being used any longer.

Audio Input Devices (e.g. microphones)

When the audio input devices of the system are changed the player raises the "MediaSystemAudioDevicesChanged" event that can be used to, for example, stop the player (if the used device is disabled or removed and the player only plays an audio input device), customize menus and notify users.

The "MediaSystemAudioDevicesChanged" event contains information about the changed device, what has changed, and whether it is an input or output device. In the source code of the "PVSPlayerExample" application, the "Webcam Window" file contains examples of how to handle these system device changes.

A PVS.MediaPlayer player also offers events for when one of the devices used is changed by a user (for example, by choosing from a menu).

Image 7

17. Playing Images

A player can play images, such as jpeg and png files, in the same way as video files. You don't need to do anything special for that, the player automatically converts an image into an mp4 video file when you start playing an image. You can play an image as any other media file, using the player's playback method, for example:

myPlayer.Play (@"C:\Pictures\myPicture.jpg", panel1);

You can use the player's Image class to change some of the properties associated with image playback, such as how long to play the images, for example:

myPlayer.Images.Duration = 10; // default 5 seconds

Since the images are played as video files, you can use all the options of the player you usually use when playing video files.

18. Losing the Gap

Normally there is a short "gap" between playing two consecutive media files. This is simply caused by ending one file and starting the next. A PVS.MediaPlayer player can smooth the transition between two video files by holding (not wiping out) the image of a finished video file until the next one starts playing. This may look more pleasant especially when playing images. Video files usually fade in and out themselves, so there is always a bit of a gap between two videos.

You can instruct the player not to clear the player's display at the end of playing a video file with, for example:

myPlayer.Display.Hold = true;

When playback of consecutive media files has ended, for example at the end of a playlist, the player's display should be cleared again. Because the player does not know when media files have finished playing, you have to indicate this yourself with, for example:

myPlayer.Display.Hold = false;

or if you don't want to completely disable the Hold option but just clear the display:


In some cases, the player will automatically clear the player's display, such as when an error occurs during playback or when playback is stopped by the user (myPlayer.Stop). But if an error occurs while starting a (next) media file, you should clear the display yourself if desired. In this case, the player does not automatically clear the display so that you can ignore the error and continue playing subsequent files.

19. From Here On...

PVS.MediaPlayer provides easy access to many standard and advanced media player functions and provides a stable environment for playing media files. It automatically takes care of internal and system changes (such as changes to the sound device used) so that you can fully focus your creativity on playing media files the way you like.

As mentioned, this article provides only a limited overview of the functions offered by the PVS.MediaPlayer library. But that shouldn't be a problem, because the beautiful IntelliSense from Visual Studio is well used by the library and, together with the clearly structured interface, can easily guide you through even the most advanced player options. And then, of course, there are the richly documented example apps, "How To ..." and the large player demo "PVSPlayerExample". And if you still have questions, just ask them here in the comments section at the bottom of this article.

Happy coding!

Animation by Arjan Westerdiep (


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Peter Vegter
United States United States
No Biography provided

Comments and Discussions

AnswerRe: jump to specific time in video Pin
Peter Vegter24-Jul-14 6:41
MemberPeter Vegter24-Jul-14 6:41 
QuestionFaster Seeking Pin
topazas10-May-14 12:57
Membertopazas10-May-14 12:57 
AnswerRe: Faster Seeking Pin
Peter Vegter10-May-14 14:11
MemberPeter Vegter10-May-14 14:11 
GeneralRe: Faster Seeking Pin
topazas11-May-14 1:08
Membertopazas11-May-14 1:08 
GeneralRe: Faster Seeking Pin
Peter Vegter11-May-14 3:27
MemberPeter Vegter11-May-14 3:27 
GeneralRe: Faster Seeking Pin
topazas11-May-14 5:21
Membertopazas11-May-14 5:21 
QuestionExcellent work Pin
nebojsa_j23-Apr-14 7:31
Membernebojsa_j23-Apr-14 7:31 
AnswerRe: Excellent work Pin
Peter Vegter23-Apr-14 9:53
MemberPeter Vegter23-Apr-14 9:53 
You're welcome and thank you!

PVS.AVPlayer (MCI) is intended primarily for easy playback of media files, with some special options added, and less suitable for 'low-level' manipulation of audio and video. However, you can get the frame rate of a (playing) movie with an MCI command. Although there's not a special function for it in PVS.AVPlayer, you can use the direct MCI access options available:
string result;
myPlayer1.MCIRequest("status", "frame rate", out result);
if (myPlayer1.LastError) MessageBox.Show(myPlayer1.LastErrorString);
else MessageBox.Show("Frame Rate (x 1000) = " + result);
// ... total frames: multiply by the duration of the file

For more information about MCI commands, please see:
For more information of a mediafile you could use other (.NET) 'techniques', like extracting (Windows Explorer) metadata of the file or by using other media (info) libraries (please search the internet).


modified 23-Apr-14 16:39pm.

QuestionNice Component... Pin
Edan Tenanan18-Apr-14 21:41
MemberEdan Tenanan18-Apr-14 21:41 
AnswerRe: Nice Component... Pin
Peter Vegter18-Apr-14 23:16
MemberPeter Vegter18-Apr-14 23:16 
Questionplay a http url? Pin
benny8566943-Apr-14 21:36
Memberbenny8566943-Apr-14 21:36 
AnswerRe: play a http url? Pin
Peter Vegter4-Apr-14 0:42
MemberPeter Vegter4-Apr-14 0:42 
AnswerRe: play a http url? Pin
Peter Vegter4-Apr-14 8:54
MemberPeter Vegter4-Apr-14 8:54 
QuestionGreat article ! Pin
Volynsky Alex3-Apr-14 12:21
professionalVolynsky Alex3-Apr-14 12:21 
AnswerRe: Great article ! Pin
Peter Vegter3-Apr-14 15:39
MemberPeter Vegter3-Apr-14 15:39 
GeneralRe: Great article ! Pin
Volynsky Alex3-Apr-14 20:10
professionalVolynsky Alex3-Apr-14 20:10 
QuestionExcellent work .. congratulations Pin
caoc730-Aug-13 15:42
Membercaoc730-Aug-13 15:42 
AnswerRe: Excellent work .. congratulations Pin
Peter Vegter30-Aug-13 21:35
MemberPeter Vegter30-Aug-13 21:35 
GeneralControl myPlayer1.ShuttleSlider Pin
caoc731-Aug-13 3:42
Membercaoc731-Aug-13 3:42 
GeneralRe: Control myPlayer1.ShuttleSlider Pin
Peter Vegter31-Aug-13 9:15
MemberPeter Vegter31-Aug-13 9:15 
GeneralThank you very much Pin
caoc73-Sep-13 4:48
Membercaoc73-Sep-13 4:48 
GeneralRe: Thank you very much Pin
Peter Vegter3-Sep-13 5:58
MemberPeter Vegter3-Sep-13 5:58 
QuestionCode of the Player Pin
Johann Krenn20-Aug-13 0:34
MemberJohann Krenn20-Aug-13 0:34 
GeneralMy vote of 5 Pin
DrABELL19-Aug-13 14:19
professionalDrABELL19-Aug-13 14:19 
AnswerRe: My vote of 5 Pin
Peter Vegter19-Aug-13 15:34
MemberPeter Vegter19-Aug-13 15:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 14 Sep 2010


345 bookmarked