Copyright © 2010 PVS The Netherlands - Free to Use, Not for Sale.

Introduction

This is an MCI Wrapper Class Library for .NET developers for easy but powerful playback of movies and/or music from within your application using Microsoft Windows built-in Media Control Interface (MCI), adding:

  • display formatting
  • multiple fullscreen modes
  • display overlays
  • true repeat
  • and more

All code examples in this textfile are copied from a working application.

  • PVS.AVPlayer requires Microsoft Windows .NET Framework 3.5 or higher.
  • PVS.AVPlayer Example #1 - DisplayModes requires Microsoft Windows .NET Framework 4.0 or higher.
  • PVS.AVPlayer Example #2 - FullScreenModes requires Microsoft Windows .NET Framework 3.5 or higher.
  • PVS.AVPlayer was created using Microsoft Visual Studio 2010 Express Edition and Microsoft Windows 7.
  • PVS.AVPlayer does not contain any viruses, spyware, advertisements or other malware, does not collect any information, changes nothing permanently to your computer and does 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.

Brief Instructions On How To Use PVS.AVPLAYER

Contents

  1. Adding PVS.AVPlayer to your Project
  2. Creating a Player
  3. Playing a mediafile
  4. Player Display
  5. FullScreen Display
  6. So Far...
  7. Display Overlay
  1. List of Commands

I. Adding PVS.AVPlayer to your Project

Before you can use the PVS.AVPlayer library, you have to add a reference to it in your project.

First download "PVS.AVPlayer.zip", if you haven't already done so, and unpack the library (DLL) anywhere you like on your harddisk. Later on, Visual Studio will automatically copy the DLL to your project output folder (bin\Debug) together with the executable (application) you have created.

Next, create a new project (you can also use an existing project of course) 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 tab and locate and select "PVS.AVPlayer.dll". Now you're ready to use PVS.AVPlayer.

Finally, you might want to include the library namespace in your project files. It allows shorter names to be used. Type at the top of every project file that uses the library:

using PVS.AVPlayer;

If you don't want to get into the examples below, here's how you can play a movie (or music):

Player myPlayer = new Player();
myPlayer.Play(@"C:\myMovie.mpg");

To stop playing and remove myPlayer, use:

myPlayer.Dispose(); 

II. Creating a Player

To play a mediafile (movie or music), you'll first have to create a 'Player'.

In your project, you can create as many Players as you like and also get rid of them again when you don't need them anymore. You can use them simultaneously, even to play - in most cases - the same mediafile.

Usually you would create one or more Players to be used throughout the project, so you declare them at the top of your project, outside any Sub but within a Class (global). In the next example, the name of the Player is "myPlayer1" and a few lines of code are added to use one of the events raised by the Player.

A Player can inform you about two types of events:

  1. MediaEnd tells you that a mediafile has finished playing.
  2. MediaRepeat tells you that a mediafile has finished playing and is repeated.

You can 'catch' these events with your Player EventHandler and act upon it. For instance, in case of a MediaEnd event, you might want to play another (next) mediafile.

Adding a Player with EventHandler to a new Windows Forms Application project:

using PVS.AVPlayer;

namespace MyProject
{
    public partial class Form1 : Form
    {
        Player myPlayer1;

        public Form1()
        {
            InitializeComponent();

	   myPlayer1 = new Player();
            myPlayer1.MediaEnd += new Player.MediaEndEventHandler(myPlayer1_MediaEnd);
        }

        private void myPlayer1_MediaEnd(object sender)
        {
	    // ... your eventhandling code
        }
    }
}

III. Playing a Mediafile

To play a mediafile, you can use one of the Player's Play methods, but before you do so, you'll need the path and filename of the mediafile you want to play. Later on you might want to add an OpenFileDialog to your project to select mediafiles, but for now the name of a mediafile is just added to the project (replace "C:\MyMovies\MyMovie.mpg" by the path and filename of one of your movies).

Also, if you're about to play a movie, you might want to tell the Player where to display the movie. If you don't, the Player will open a new window to display the movie (not the MCI window).

To create a (tiny) mediaplayer, add the PlayMedia method (see below) to the code and add (not on top of each other) a panel (panel1) and a button (button1) to the project's form. Double-click the button and add the PlayMedia instruction in the automatically created buttonclick handler. The project code now looks something like this:

using PVS.AVPlayer;

namespace MyProject
{

    public partial class Form1 : Form
    {
        Player myPlayer1;
	string myMovie = @"C:\MyMovies\MyMovie.mpg";

        public Form1()
        {
            InitializeComponent();

	   myPlayer1 = new Player();
            myPlayer1.MediaEnd += new Player.MediaEndEventHandler(myPlayer1_MediaEnd);
        }

        private void myPlayer1_MediaEnd(object sender)
        {
	    // ... your eventhandling code
        }

	private void PlayMedia(string fileName)
	{
            myPlayer1.Play(fileName, panel1);

	    if (myPlayer1.LastError != 0)
	    {
		MessageBox.Show(myPlayer1.LastErrorString);
	    }
	    else
	    {
		// ... we'll put something here later on
	    }
	}

	private void button1_Click(object sender, EventArgs e)
        {
            PlayMedia(myMovie);
        }
    }
}

Press F5, click the button on your form and see what happens.

IV. Player Display

You can display the video of a mediafile using a form or almost any other type of control, like a picturebox, label or panel. A panel might be the best choice because it has the least resources attached.

Any form or suitable control will do, it doesn't have to be in the same class as the code. If you have a second form, you can display the video on that form, controlling it from the first form.

You can set or change the display of a player not only with the play method (as above), but anytime you like, even when a movie is playing, with:

myPlayer1.Display = panel1;		// panel1 as display
myPlayer1.Display = this;		// the form as display
myPlayer1.Display = Form2.panel1;	// panel1 on another form as display
myPlayer1.Display = null;		// no display

You only have to set the player's display once, the player will 'remember' which display to use (as with all other player settings).

If you don't attach a display to a player, the player will create a new window to display the video. You can have full control over this window, but it's probably not always what you want.

If you don't want to display video at all (but only hear the sound), you can disable the display of video with:

myPlayer1.VideoEnabled = false;

If you just want to play musicfiles, like mp3, you don't have to use a display or disable the display of video:

myPlayer1.Play(myMusic);

DisplayModes

Video can be shown in different ways on the player's display by setting the display's displaymode. You can have the video fill the entirely display, zoom it or use its original size.

You can set the player's displaymode with (among others):

myPlayer1.DisplayMode = DisplayMode.Stretch;	      // fill the display 
					      //(some movies can't be 'stretched')
myPlayer1.DisplayMode = Displaymode.ZoomAndCenter;  // as large as possible preserving 
					      // size ratio; default setting

You can set the position and size of the video at will by setting myPlayer1.VideoBounds. When you do so, the displaymode is set to DisplayMode.Manual. The position is relative to the top-left of the player display (panel1). With the manual displaymode, the movie is not resized (as with the other displaymodes) when the size of the player display changes.

myPlayer1.VideoBounds = new Rectangle(-10, -20, 1000, 750);	// left = -10, 
					// top = -20, width = 1000, height = 750
myPlayer1.VideoBounds = myPlayer1.Display.DisplayRectangle;	// same size as 
							// player display

The example application "PVS.AVPlayer Example #1 - DisplayModes" shows the displaymodes.

Note: A movie is displayed (sort of) on top of a display control (panel1). If you click on the part of the control where the movie is being displayed, the control (panel1) does not 'receive' the mouseclick (exception: right-click for contextmenu). The same goes for most other events. Also any control inside the display control is overwritten (not visible) by the movie. This will probably pose a problem with fullscreen display only. There are some ways to overcome this, using a contextmenu being one of them (and you can show controls (like a button) on top of a movie when the player display is not their 'parent' control or using an display overlay - see FullScreen display and Display Overlays)).

V. FullScreen Display

PVS.AVPlayer has built-in options to have a movie displayed using the entire screen, hiding the desktop, taskbar and anything else. However, you still can have other windows (and the taskbar) to be displayed in front of your fullscreen application.

With PVS.AVPlayer, you can not only show a form fullscreen but also a player display, meaning that you can show a player display using the entire screen even if it's smaller than the form it's on.

You can switch to fullscreen display with:

myPlayer1.FullScreen = true;

Before adding this option to the example code, we must have some way to return to normal display, otherwise we'll be stuck in fullscreen display.

The best way would be to add a contextmenu to panel1 or even an 'always on top' controller form (see 'Note' above), but for now we're just going to 'catch' keypress events for the form.

To detect any keypress on the active form (even when one of the controls on it has focus), you have to set the form's KeyPreview property to 'true'. The form's keyeventhandler (Form1_KeyDown - see below) then 'toggles' fullscreen display when the spacebar is pressed (if you are ever going to have textinput on your form, you'll have to change this).

Also a few other things have been added to the code:

  • Some more declarations at the top (variables used with the MediaEnd event and 'button on top')
  • More player initialization (display and displaymode are set before using the play method)
  • The player's MediaEnd event now plays 'next' mediafiles
  • Show a control (button1) on top of a movie (see SetFullScreen method).
using PVS.AVPlayer;

namespace MyProject
{
    public partial class Form1 : Form
    {
        Player myPlayer1;
	string myMovie = @"C:\MyMovies\MyMovie.mpg";
        string myMovie2 = @"C:\MyMovies\MyMovie2.avi";
	int totalMovies = 2;
	int movieToPlay = 0;
	point buttonLocation;

        public Form1()
        {
            InitializeComponent();

	    myPlayer1 = new Player();
             myPlayer1.MediaEnd += new Player.MediaEndEventHandler(myPlayer1_MediaEnd);

	    myPlayer1.Display = panel1;
	    myPlayer1.DisplayMode = DisplayMode.Stretch;

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

        private void myPlayer1_MediaEnd(object sender)
        {
            movieToPlay += 1;
            if (movieToPlay > totalMovies) movieToPlay = 1;

            switch (movieToPlay)
            {
                case 1:
                    PlayMedia(myMovie);
                    break;
                case 2:
                    PlayMedia(myMovie2);
                    break;
            }
        }

        private void PlayMedia(string fileName)
        {
            myPlayer1.Play(fileName);

            if (myPlayer1.LastError != 0)
            {
                MessageBox.Show(fileName + "\r\n\r\n" + myPlayer1.LastErrorString);
                ResetFullScreen();
            }
            else
            {
                SetFullScreen();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            myPlayer1_MediaEnd(this);
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                if (myPlayer1.FullScreen)
		{
		    ResetFullScreen();
		}
		else
		{
		    SetFullScreen();
		}
                e.Handled = true;
            }
        }

	private void SetFullScreen()
	{
	    if (!myPlayer1.FullScreen)
	    {
		buttonLocation = button1.Location;
		myPlayer1.FullScreen = true;
		button1.Location = new Point
			(myPlayer1.Display.Width - button1.Width - 24, 24);
		button1.BringToFront();
	    }
	}

	private void ResetFullScreen()
	{
	    if (myPlayer1.FullScreen)
	    {
		myPlayer1.FullScreen = false;
		button1.Location = buttonLocation;
	    }
	}
    }
}

Besides showing the player's display (panel1) fullscreen, PVS.AVPlayer has two more fullscreen options. The fullscreen options are:

  1. FullScreenMode.Form shows the form (the player display is on) fullscreen.
  2. FullScreenMode.Parent shows the parent control (the player display is in) fullscreen.
  3. FullScreenMode.Display shows the player display fullscreen (default setting).
myPlayer1.FullScreenMode = FullScreenMode.Form;

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

The example application "PVS.AVPlayer Example #2 - FullScreenModes" shows the fullscreenmodes.

VI. So Far...

One form, one button and one panel. That doesn't even come close to being a mediaplayer (there's not even a 'Stop' button). Still, it already has everything in it to play a movie, and more.

The code was kept as short as possible, while trying to demonstrate the basics of PVS.AVPlayer. Just to give an idea how to start with PVS.AVPlayer. The code could do with some rewriting for a real application but the building blocks of it can be used as a starting point. You can have only a few lines of code in your application to play a movie or even write your own home mediaplayer.

There are two more options that should be mentioned: the PlayerStartInfo and display overlays.

PlayerStartInfo

You can set the player's options directly, as shown in the example above, but you can also set them all at once when you start playing a new movie. You'll find the same options in a PlayerStartInfo as with the direct options. Using a PlayerStartInfo may be a more 'smooth' and convenient way to start a movie. For instance, the fullscreen option can be set at the same time as a movie starts playing.

Using PlayerStartInfo:

PlayerStartInfo myStartInfo1;	// create PlayerStartInfo

myStartInfo1 = myPlayer1.StartInfo; 	// get the player's startinfo, 
				// so you don't have to set all values

myStartInfo1.FileName = myMovie;
myStartInfo1.Display = panel1;
myStartInfo1.StartPosition = 120000;	// (int)(TimeSpan.Parse
				// ("00:02:00").TotalMilliseconds);
myStartInfo1.EndPosition = 240000;	// (int)(TimeSpan.Parse
				//("00:04:00").TotalMilliseconds);
myStartInfo1.Repeat = true;

myPlayer1.Play(myStartInfo1);	// start a movie using PlayerStartInfo

VII. Display Overlay

With a PVS.AVPlayer Display Overlay, you can show about anything on top of a movie (with full transparency). A PVS.AVPlayer is a form, just like the ones you use in your Windows Forms Application projects. And as you can do about anything with a form, you can do about anything with a display overlay. A form can be used to display anything you like, such as text, pictures and movies. So can a display overlay. And as a form can have a full program attached, a display overlay is fully programmable.

Actually, PVS.AVPlayer doesn't do much more than trying to keep the overlay (form) the same size and at the same position as the player's display.

Every PVS.AVPlayer player can have its own - or a shared - display overlay, which can be replaced by another overlay any time. You can design a display overlay (form) with the Visual Studio designer or write the code yourself.

PVS.AVPlayer can use almost any form you like inside your project as a display overlay (you can't use a form as an overlay on the same form). All you have to do is 'tell' a player which form to use as a display overlay:

Form2 myOverlay1 = new Form2();	// create a new copy of Form2, 
				// not always necessary but recommended
myPlayer1.Overlay = myOverlay1;	// attach it to the player

Just try out what you can (or can't) do with a display overlay. It's up to you and your imagination, ideas and designing and programming skills.

Some Remarks

To make a display overlay transparent, PVS.AVPlayer sets the form's TransparencyKey property to the backgroundcolor of the form. If you don't want the backgound to be transparent but want to use one of the foregroundcolors for transparency (for 'see through' shapes) you can set the form's TransparencyKey yourself (if it's set, PVS.AVPlayer doesn't change it).

If the Overlay has to be resizable, then you can have the controls and text on the overlay to be resizable also. For text this works fairly well, but resizing controls may not always give the desired results if the overlay is resized too many times. Use the property OverlayAutoScale to resize text and controls. If you set the MinimumSize property of a control, the text inside the control will not be resized.

Normally an overlay is shown only when a movie is being played. If you want it to be always visible, you can set the OverlayHold property to 'true'. An overlay can be displayed using the size of the movie or the size of the player display. Use the OverlayMode property to set the overlay size.

If you want to use an overlay for textinput or have selectable controls (like buttons) on it, you can set the property OverlayCanFocus to 'true'.

To avoid visible 'edges' around text on a transparent overlay, use a backgroundcolor for the form that is close to the color of the text. Setting the form's opacity a little lower than 100% 'softens' text and other items on a transparent display overlay.

The example application "PVS.AVPlayer Example #1 - DisplayModes" also shows two simple display overlays.

A. List of Commands

Methods and properties of a PVS.AVPlayer Player.

Most of them return an errorcode (which is also available from LastError; 0 = No Error).

Use as in (examples; consider using PlayerStartInfo):

myPlayer1.Play(myMovie, panel1, true);
myPlayer1.Overlay = myOverlay1;
myPlayer1.FullScreen = true;
myPlayer1.Paused = !myPlayer1.Paused;
myPlayer1.Position += 1000;
Play plays a mediafile
PausePlaying pauses a playing mediafile
ResumePlaying resumes playing a paused mediafile
StopPlaying stops playing a mediafile
Playing returns 'true' if a mediafile is playing (also when playing is paused), otherwise 'false'
Paused returns 'true' if a mediafile is paused, otherwise 'false'
Repeat repeats playing a mediafile from StartPosition (default 0: begin of file) to EndPosition (default 0: end of file)
Speed sets the speed with which the mediafile is played (normal speed: 1000, e.g. half speed: 500, double speed: 2000)
Position gets or sets the playing position of the playing mediafile in milliseconds
StartPosition gets or sets the playing start position in milliseconds (0 = begin of file; also used with Repeat)
EndPositiong gets or sets the playing end position in milliseconds (0 = end of file; also used with Repeat)
Length gets the length (duration) of the playing mediafile in milliseconds
GetLenghtOf gets the length (duration) of a mediafile (on disk) in milliseconds
ReWind sets the play position (back) to the StartPosition
Skip sets the play position relative to the current position in seconds (not milliseconds)
Display gets or sets the form or control to display movies
DisplayMode gets or sets the size and position of the movie within the display (e.g. DisplayMode.Stretch)
DisplaySize gets the size of the display
AudioVolume gets or sets the volume of the audio (value 0 (silent) to 1000)
AudioBalance gets or sets the balance of the audio (value 0 (left), 500 (center) to 1000 (right))
AudioEnabled gets or sets a value indicating whether audio is enabled
HasAudio returns 'true' if a mediafile contains audio (sound), otherwise 'false'
VideoBounds gets or sets the size and position of the video within the display (sets displaymode to DisplayMode.Manual when set)
VideoEnabled gets or sets a value indicating whether video is enabled
VideoSourceSize gets the source (original) size of the playing movie
HasVideo returns 'true' if a mediafile contains video, otherwise 'false'
FullScreen gets or sets fullscreen display
FullScreenMode gets or sets the fullscreen displaymode (e.g. FullScreenMode.Form)
Overlay gets or sets the form to use as display overlay
OverlayAutoScale gets or sets a value indicating whether the contents of the overlay will be scaled when the size of the overlay has changed
OverlayCanFocus gets or sets a value indicating whether an overlay can be activated for input and selection
OverlayEnabled gets or sets a value indicating whether the display of the overlay is enabled
OverlayHold gets or sets a value indicating whether the overlay is always shown, even if no movie is playing
OverlayMode gets or sets the overlaymode (e.g. OverlayMode.Video)
OverlaySize gets the size of the overlay
LastError gets the code of the last error that has occurred
LastErrorString gets a description of the last error that has occurred
GetErrorString gets a description of the specified errorcode
Reset resets all player settings to their default values
Dispose disposes a player (use when ending the application, otherwise also set the player to null)
Version gets the version code of PVS.AVPlayer
VersionString gets the version string of PVS.AVPlayer
VersionStringShort gets the short version string of PVS.AVPlayer

History

  • August 2010 - PVS.AVPlayer version 0.1
  • December 2010 - PVS.AVPlayer version 0.11
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"