Click here to Skip to main content
13,905,355 members
Click here to Skip to main content

Stats

741.3K views
30.1K downloads
281 bookmarked
Posted 14 Sep 2010
Licenced CPOL

PVS.AVPlayer - MCI Audio and Video Library

, 7 Aug 2018
Windows Media Control Interface (MCI) library with many added features
PVS.AVPlayer
PVS.AVPlayer .NET 2.0
PVS.AVPlayer.XML
PVS.AVPlayer .NET 3.0
PVS.AVPlayer.XML
PVS.AVPlayer .NET 3.5
PVS.AVPlayer.XML
PVS.AVPlayer .NET 4.0
PVS.AVPlayer.XML
PVS.AVPlayer .NET 4.5
PVS.AVPlayer .NET 4.5.1
PVS.AVPlayer.XML
PVS.AVPlayer .NET 4.5.2
PVS.AVPlayer.XML
PVS.AVPlayer.XML
PVS.AVPlayer .NET 4.6
PVS.AVPlayer.XML
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer .NET 4.6.1
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer .NET 4.6.2
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer .NET 4.7
PVS.AVPlayer .NET 4.7.1
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer .NET 4.7.2
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer.dll
PVS.AVPlayer.XML
PVS.AVPlayer All Source Code
AVPlayerExample
AVPlayerExample
AVPlayerExample.csproj.user
bin
Debug
PVS.AVPlayer.XML
Release
Dialogs
Display Overlays
obj
Debug
Release
x86
Debug
Release
Properties
Resources
Crystal Italic1.ttf
WingDings3a.ttf
Voice Recorder
FolderView
FolderView
bin
Debug
PVS.AVPlayer.XML
Release
FolderView.csproj.user
obj
Release
x86
Debug
Release
Properties
Resources
Crystal Italic1.ttf
PVS.AVPlayer
AVPlayerExample.csproj.user
PVS.AVPlayer.dll
PVS.AVPlayer.XML
Custom Items
Native Methods
Bob.png
Crystal Italic1.ttf
Dial Green 2.png
Dial Green 4.png
Dial Green.png
Dial Red 2.png
Dial Red.png
media7.ico
media7a.ico
Media8.ico
Media8a.ico
VU Meter.png
WingDings3a.ttf
Sound Recorder
Various
About Dialog
PVS.AVPlayer.dll
PVS.AVPlayer.XML
Custom Items
FolderView.csproj.user
Debug
Bob.png
Crystal Italic1.ttf
media7a.ico
media7b.ico
Media8a.ico
Media8b.ico
Subtitles Overlay
Various
How To (C#)
PVSAVPlayerHowTo
bin
Debug
PVS.AVPlayer.dll
PVS.AVPlayer.XML
Release
obj
Debug
Release
Properties
How To (VB.NET)
PVSAVPlayerHowToVB
bin
Debug
PVS.AVPlayer.dll
PVS.AVPlayer.XML
Release
My Project
Application.myapp
obj
Debug
Release
PVSAVPlayerHowTo.vbproj.user
PVS.AVPlayer Examples
AVPlayerExample.ex_
FolderView.ex_
AVPlayerExample.exe
FolderView.exe
PVS.AVPlayer.dll
#region Usings

using PVS.AVPlayer;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;

#endregion

namespace PVSAVPlayerHowTo
{
    public partial class Form1 : Form
    {
        /*
            PVS.AVPlayer 0.91 Example Application - How To...

            This small sample application shows how to use some of the the more 'special' options
            of the player part of the PVS.AVPlayer library:

             1. add a display overlay
             2. display overlay always visible - from application start
             3. add one or more display clones
             4. add a position slider controlled by the player
             5. get continuous playback position information
             6. add audio sliders controlled by the player
             7. get changed audio value information
             8. get continuous audio output level information
             9. get mouse events on display, movie or overlay
            10. get media finished playing information
            11. get media subtitles
            12. get media tag information (MP3 (ID3) and WMA (ASF) Tags)
            13. play (or repeat) only a part of a media file
            14. add a taskbar progress indicator
            15. drag a form by dragging a player's display window
            16. add an info label to the player's position slider
            17. change the shape of the player's display window
            18. using media signals
            19. automatically hide the mouse cursor during media playback

            These options are initialized and commented in the constructor (method Main: Form1()) of this class.

            Many options in de PVS.AVPlayer library are available even when no media is playing, they
            are 'Player settings' not 'Media settings', e.g.: Display settings (e.g. fullscreen),
            Audio settings (volume/balance), Start/EndPosition, Pause/Resume and others.

            If you have questions about using the PVS.AVPlayer library or this sample application, do not hesitate
            to ask a question in the PVS.AVPlayer article's comments on CodeProject:
            https://www.codeproject.com/Articles/109714/PVS-AVPlayer-MCI-Audio-and-Video-Library

            Peter Vegter
            August 2018, The Netherlands
        */


        // **** Class Fields **************************************************************************

        #region Class Fields

        private Player          myPlayer;
        private Overlay         myOverlay;          // in file 'Overlay.cs'

        private int             shapeStatus;        // shapes - 0:none, 1:oval, 2:none, 3:rounded, 4:none, 5:star

        private InfoLabel       myInfoLabel;
        private StringBuilder   myInfoLabelText     = new StringBuilder(64);

        // used with drawing audio output levels
        // levelUnit is the size of 1 unit (of 32767) and 140 is the width of panel4 and panel5
        private double          levelUnit           = 140; // 32767.0; changed in PVS.AVPlayer version 0.91
        private int             leftLevel;
        private int             rightLevel;

        private TagInfo         tagInfo;            // media (audio mp3/wma/asf) tag info
        private OpenFileDialog  myOpenFileDlg;      // used with selection of media to play
        private const string    OPENMEDIA_DIALOG_FILTER =
            " Video Files (*.*)|*.asf;*.avi;*.bik;*.divx;*.dvx;*.f4v;*.flv;*.h264;*.hdmov;*.m2ts;*.mkv;*.mod;*.mov;*.mp2;*.mp4;*.mpeg;*.mpeg4;*.mpg;*.mpv;*.ogg;*.ogm;*.ogv;*.qt;*.rm;*.rms;*.rmvb;*.swf;*.ts;*.vfw;*.vob;*.webm;*.wmv;*.xvid|" +
            " Audio Files (*.*)|*.3gp;*.aa;*.aac;*.aiff;*.amr;*.ape;*.flac;*.m4a;*.mid;*.midi;*.mka;*.mp3;*.mpc;*.ogg;*.opus;*.ra;*.rm;*.wav;*.webm;*.wma;*.wv|" +
            " Image Files (*.*)|*.bmp;*.gif;*.img;*.jpeg;*.jpg;*.png;*.tga;*.tiff|" +
            " All Files|*.*";
        private bool            isDisposed;         // used with cleaning up

        #endregion


        // **** Main **********************************************************************************

        #region Main

        public Form1()
        {
            InitializeComponent();                          // this call is required by the designer

            myPlayer                    = new Player();     // create a player
            myPlayer.Display.Window     = panel1;           // and set its display to panel1
            myPlayer.Repeat             = true;             // repeat media playback when finished

            myPlayer.SleepDisabled      = true;             // prevent the computer from entering sleep mode

            // create a file selector
            myOpenFileDlg = new OpenFileDialog()
            {
                Title = "Play Media",
                Filter = OPENMEDIA_DIALOG_FILTER,
                FilterIndex = 4                             // 4 = all files
            };


            // You may want to add one or more of the following options to your player:


            // **** 1. DISPLAY OVERLAY ****************************************************************

            // A display overlay is a Form that allows you to display items on top of a movie.
            // The sample overlay 'Overlay' is created with the designer - please see Overlay.cs
            myOverlay = new Overlay();             // create (an instance of) the overlay
            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;



            // **** 2. DISPLAY OVERLAY ALWAYS VISIBLE *************************************************

            // A display overlay is usually only shown when media is playing, but if you want to always
            // show the overlay you can use: myPlayer.Overlay.Hold = true;

            // The player's display has to be created and visible for this, so if you want
            // to show the overlay right from the start of your application (without media playing) you
            // have to put the 'Overlay.Hold' instruction in the Form1.Shown event handler (see below).



            // **** 3. DISPLAY CLONES *****************************************************************

            // For special purposes you can create one or more player display clones (display copies).
            // Display clones require sufficient computing (cpu) power and may slow some computers:
            myPlayer.DisplayClones.AddRange(new Control[] { panel2, panel3 });

            // cpu load can be reduced by lowering the framerate, quality or size of the clones:
            // e.g. myPlayer.DisplayClones.FrameRate = 10;

            // You can also 'stretch' display clones (as with displaymode.stretch of the main display):
            myPlayer.DisplayClones.SetLayout(panel2, CloneLayout.Stretch);

            // To remove display clones from the player use one of the clones remove methods, e.g.:
            // myPlayer.DisplayClones.Remove(panel2);



            // **** 4. POSITION SLIDER ****************************************************************

            // The player can control your media playback position slider (trackbar) with:
            myPlayer.Sliders.Position = trackBar1;

            // The position slider controlled by the player is only for input by the user. The value of
            // the slider should not be set from code. If you want to change the playback position (and
            // the slider value), use the position methods of the player, for example:
            // myPlayer.Position.FromBegin = TimeSpan.FromSeconds(30).

            // To remove a slider from the player set the slider to null:
            // myPlayer.Sliders.Position = null;



            // **** 5. POSITION TIME ******************************************************************

            // If you want to display the elapsed and/or remaining media playback time (or use your
            // 'own' position slider) you can get continuous media playback positions information with:
            myPlayer.Events.MediaPositionChanged += MyPlayer_MediaPositionChanged; // please see below

            // To unsubscribe from the event you can use:
            // myPlayer.Events.MediaPositionChanged -= MyPlayer_MediaPositionChanged;



            // **** 6. AUDIO SLIDERS ******************************************************************

            // The player can also control your audio sliders (trackbars) with:
            myPlayer.Sliders.AudioVolume = trackBar2;     // audio volume slider
            myPlayer.Sliders.AudioBalance = trackBar3;    // audio balance slider

            // The audio sliders controlled by the player are only for input by the user. The values of
            // the sliders should not be set from code. If you want to change the audio properties (and
            // the sliders values) of the player, use the audio methods of the player, for example:
            // myPlayer.Audio.Volume = 500;

            // To remove a slider from the player set the slider to null:
            // myPlayer.Sliders.AudioVolume = null;



            // **** 7. AUDIO VALUES *******************************************************************

            // To get the changed values of the player's audio volume and balance use these events:
            myPlayer.Events.MediaAudioVolumeChanged += MyPlayer_MediaAudioVolumeChanged; // see handler below
            myPlayer.Events.MediaAudioBalanceChanged += MyPlayer_MediaAudioBalanceChanged; // see below

            // To unsubscribe from the event you can use:
            // myPlayer.Events.MediaAudioVolumeChanged -= MyPlayer_MediaAudioVolumeChanged;



            // **** 8. AUDIO OUTPUT PEAK LEVELS *******************************************************

            // From version 0.91, the use of the 'Stereo Mix' device has been replaced by the use of
            // some functions from the Windows Core Audio Api (Windows Vista or higher only).

            // Audio output levels can be used to display the peak levels of the system's default audio
            // output device (eg speakers) in a numeric or graphical (eg level/vu meters) form or for
            // other purposes.

            // To get the audio peak values from the system default audio device you can use the
            // MediaPeakLevelChanged event of the player:

            myPlayer.Events.MediaPeakLevelChanged += MyPlayer_MediaPeakLevelChanged; // see handler below

            // check if there is an audio device or if this function is not supported (Windows Vista or
            // higher) with: if (myPlayer.LastError) {...}

            // The values received in the eventhandler are between 0.0 and 1.0 (inclusive) or -1 when media
            // playback has paused, stopped or ended - for every audio channel (usually 2 for stereo).

            // To unsubscribe from the event you can use:
            // myPlayer.Events.MediaPeakLevelChanged -= MyPlayer_MediaPeakLevelChanged;



            // **** 9. MOUSE EVENTS ON DISPLAY, MOVIE OR OVERLAY **************************************

            // Note: Because of the new drag option (see item #15 below) this option is not used.

            // Normally you don't get mouse events from a (MCI) movie window, but with this you can:
            // myPlayer.Events.MediaMouseClick += myPlayer_MediaMouseClick;
            // it combines mouse events for display, movie and overlay in one, so you always can get a
            // mouse event (click, move, wheel etc.) on a player's display. Also see: myPlayer.PointTo

            // For completeness, mouse click event handlers are added for the display clones which are
            // 'normal' controls with 'normal' mouse events:
            panel2.MouseDown += Clone_MouseClick; // using mousedown and not mouseclick for speed
            panel3.MouseDown += Clone_MouseClick; // fast mouseclick = dubbelclick and not click



            // **** 10. MEDIA FINISHED PLAYING ********************************************************

            // You may want to know when media has finished playing to play other (next) media and/or
            // stop certain processes (e.g. animation on a display overlay).
            // To detect that media has finished playing just subscribe to the MediaEnded event:
            myPlayer.Events.MediaEnded += MyPlayer_MediaEnded;  // see eventhandler below

            // You don't want to start playing next media from the MediaEnded event before all processes
            // have been notified that the previous media has finished playing, so there's another event:
            myPlayer.Events.MediaEndedNotice += MyPlayer_MediaEndedNotice;  // see eventhandler below
            // you can use this event to just stop any active processes (and not start any new media).
            // (With the MediaStarted event you can (re)start processes when new media starts playing.)

            // To unsubscribe from the event you can use:
            // myPlayer.Events.MediaEnded -= MyPlayer_MediaEnded;



            // **** 11. MEDIA SUBTITLES ***************************************************************

            // You can get the SubRip (.srt) subtitles (if any) of the playing media by subscribing to
            // the MediaSubtitleChanged event:
            myPlayer.Events.MediaSubtitleChanged += MyPlayer_MediaSubtitleChanged; // see eventhandler below

            // By default the subtitles file should be in the same folder and with the same name (but
            // with the .srt extension) as the media file, or one of its containing folders. You can
            // specify to search in any containing folders with (0 = media file 'base' folder):
            myPlayer.Subtitles.DirectoryDepth = 1; // search base folder and containing folders 1 deep

            // If the subtitles file is located somewhere else or it has another name, you can specify
            // where to search with the myPlayer.Subtitles.Directory and/or myPlayer.Subtitles.FileName functions.
            // The Folder depth search applies also to this location.

            // There are some more convenient subtitles functions, e.g. to synchronize subtitles (TimeShift).

            // To unsubscribe from the event you can use:
            // myPlayer.Events.MediaSubtitleChanged -= MyPlayer_MediaSubtitleChanged;



            // **** 12. MEDIA TAG INFORMATION (MP3 (ID3) AND WMA (ASF) TAGS) **************************

            // You can get media tag information (MP3 (ID3) or WMA (ASF) Tags) with:
            // TagInfo info = myPlayer.Media.GetTagInfo();

            // Please see the methods PlayMedia, myPlayer_MediaEnded, myPlayer_MediaStopped and
            // DisposeTagInfo for an example of the use of the tag information option.



            // **** 13. PLAY (OR REPEAT) ONLY PART OF A MEDIA FILE ************************************

            // N.B. 'Begin' and 'End' is used to indicate the natural begin and end of media
            //      'Start' and 'Stop' is used to indicate the actual start and stop positions of media
            //      If not changed, 'Start' and 'Stop' values are the same as 'Begin' and 'End' values.

            // You can play (or repeat) only a part of a media file by specifying the start- and/or stopposition:

            // a. before media starts playing, e.g. from 00:10:15 to 00:20:00 (uses '...Next' keywords):
            //    myPlayer.Media.StartPositionNext = new TimeSpan(0, 10, 15);
            //    myPlayer.Media.StopPositionNext  = TimeSpan.FromMinutes(20);

            // b. while media is playing, e.g. finish in 10 minutes from the current position:
            //    myPlayer.Media.StopPosition = myPlayer.Position.FromBegin + TimeSpan.FromMinutes(10);



            // **** 14. ADD A TASKBAR PROGRESS INDICATOR **********************************************

            // To add a progress indicator in the taskbar button of a Form, all you have to do is instruct
            // the player to do so by specifying the Form:
            myPlayer.TaskbarProgress.Add(this);

            // You can specify any Form you like (not just the form the display of the player is on) and use
            // multiple and/or duplicate Forms.

            // You can specify the mode of the progress indicator (progress (default) or track (= 'begin to end')):
            myPlayer.TaskbarProgress.Mode = TaskbarProgressMode.Track;



            // **** 15. DRAG A FORM BY DRAGGING A PLAYER'S DISPLAY WINDOW *****************************

            // In some cases it may be convenient to drag a Form not only by its title bar but also by a
            // player's display window on the Form. You can enable this option with:
            myPlayer.Display.DragEnabled = true;

            // You can specify the mouse cursor being used while dragging the form/display window, e.g.
            myPlayer.Display.DragCursor = Cursors.SizeAll; // 'SizeAll' is also the default drag cursor

            // If you need to process other mouse events (like in item #9 above) or for other reasons,
            // you can disable this option (if you had previously enabled it) with:
            // myPlayer.Display.DragEnabled = false;



            // **** 16. ADD AN INFO LABEL TO THE PLAYER'S POSITION SLIDER *****************************

            // An Info Label is a kind of custom ToolTip that can be used with sliders (trackbars) to
            // show the current value when scrolling the slider, but can also be used in any other
            // situation where a short info / help text should be displayed.

            // Displaying slider information with an info label is made easy with the slider methods:
            // 'myPlayer.Sliders.ValueToPoint' gives the x/y-coordinate of a value on the slider and
            // 'myPlayer.Sliders.PointToValue' gives the value of the slider at a certain x/y-coordinate.
            // These methods can be used for any .net trackbar (not just the PVS.AVPlayer sliders).
            // (Without a player you can use: SliderValue.ToPoint or SliderValue.FromPoint)

            // Info Labels can be used 'everywhere', not just with sliders as in this example.
            // Just use the info label Show method to display an info label wherever you want.

            // The location of the info label is determined by the specified location in the Show method
            // and the Align (e.g. TopCenter (default)) and AlignOffset settings.
            // The size of the info label is determined by font, bordersize, etc. but the 'additional' size
            // is set with the TextMargin (or TextSize for a fixed size info label) option.

            // Most options will probably be clear, but here's some tips:
            // - border and other brushes: first set the full size of the info label (e.g. fontsize,
            // bordersize etc. etc. and, in most cases, also a 'dummy' text) then create the brush
            // - setting a fixed size info label, same as with brushes and then use:
            // myInfoLabel.TextSize = myInfoLabel.TextSize; // this sets the current size and autosize to false
            // - the order in which the settings are made can be important.

            // Create an info label for use with all sliders in this application:
            myInfoLabel                 = new InfoLabel();          // create an info label
            myInfoLabel.RoundedCorners  = true;                     // use rounded corners
            myInfoLabel.FontSize        = 9.75f;                    // set font size (same as main window)
            myInfoLabel.TextMargin      = new Padding(2, 0, 2, 0);  // fine tuning inner spacing
            myInfoLabel.AlignOffset     = new Point(0, 7);          // move closer to slider thumb


            // Here are some more examples (uncomment one at a time):

            // for the background any type of brush can be used (uncomment only this one to use):
            //LinearGradientBrush myBackBrush = new LinearGradientBrush(new Rectangle(new Point(0, 0), myInfoLabel.Size), SystemColors.ButtonHighlight, SystemColors.ButtonShadow, LinearGradientMode.Vertical);
            //myInfoLabel.BackBrush = myBackBrush;

            // or maybe no background at all (uncomment only this one to use):
            //myInfoLabel.ForeColor = Color.Red;
            //myInfoLabel.BackColor = Color.OrangeRed; // reduce visible edges around the text (anti-aliasing on transparent background)
            //myInfoLabel.BorderThickness = new Padding(0);
            //myInfoLabel.FontSize = 36;
            //myInfoLabel.Transparent = true;

            // here's a fixed size info label with a background picture (uncomment only this one to use):
            //myInfoLabel.TextMargin = new Padding(10, 70, 10, 10); // make 'room' for background image
            //myInfoLabel.ForeColor = Color.White;
            //myInfoLabel.Text = "Balance: Right 10.0"; // set size with the 'longest' possible text
            //myInfoLabel.TextSize = myInfoLabel.TextSize;  // set size + autosize off
            //myInfoLabel.BackImage = Image.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg");


            // Display an info label above the position slider's thumb using the slider's scroll event:
            trackBar1.Scroll += TrackBar1_Scroll;   // please see below

            // Same for the audio volume and balance sliders:
            trackBar2.Scroll += TrackBar2_Scroll;   // please see below
            trackBar3.Scroll += TrackBar3_Scroll;   // please see below



            // **** 17. CHANGE THE SHAPE OF THE PLAYER'S DISPLAY WINDOW *******************************

            // The shape of a player's display can be changed from the usual rectangular shape to any
            // other shape with the Player.Display.SetShape method.

            // The shape of the display, a 'region', is provided by a special method (callback)
            // called by the player when the size of the player's display window has changed.
            // PVS.AVPlayer also provides a few preset shapes.

            // You can create a display shape callback method like this (use any method name you want):
            //
            // private Region MyShapeCallbackMethod(Player player, bool videoShape, Rectangle shapeBounds)
            // {
            //     GraphicsPath path = new GraphicsPath();
            //     path.AddEllipse(shapeBounds);
            //     Region region = new Region(path);
            //     path.Dispose();
            //
            //     return region;
            // }
            //
            // you can activate the display (and optional overlay) shape with for example:
            // myPlayer.Display.Setshape(MyShapeCallbackMethod, true, false);
            // This sets the callback method and specifies using video bounds and a normal overlay.

            // You can also use one of the preset display shapes (without a callback method), e.g.:
            // myPlayer.Display.SetShape(DisplayShape.Oval);

            // Custom shaped overlays may not display (background colors) properly with display clones.
            // When using custom display shapes (eg in full-screen mode), underlying interface items may
            // become visible that were not visible with a normally formed display.

            // Display shapes are activated and deactivated with CheckBox4.CheckedChanged - see below



            // **** 18. USING MEDIA SIGNALS ***********************************************************

            // If you want to be informed that a certain media playback time has been reached, you can
            // use "media signals":
            //
            // You can create media signals:
            // a. by creating a .msf (media signals file) file to be used with certain media, or
            // b. with the Player.Signals.Add method for the next or currently playing media
            //
            // You can receive media signals by subscribing to the Player.Events.MediaSignal event:
            // myPlayer.Events.MediaSignal += MyPlayer_MediaSignal;
            //
            // The media signal eventhandler:
            // private void MyPlayer_MediaSignal(object sender, SignalEventArgs e)
            // {
            //     // signal index = e.Index;
            //     // signal message = e.Message;
            // }
            //
            // There are no "standard messages" in media signals, you must use your own "system" to
            // set and interpret the media signal messages.
            //
            // For more information please see the file "About PVS.AVPlayer versions.txt", version 0.85



            // **** 19. AUTOMATICALLY HIDE THE MOUSE CURSOR DURING MEDIA PLAYBACK *********************

            // If you want to keep the mouse cursor 'out of the way' when a movie (or any other media)
            // is playing, you can use the "Player.CursorHide" methods of the player. By specifying the
            // form(s) on which the cursor is to be hidden, the player automatically hides the cursor on
            // those forms (when in the foreground) when media is played and the mouse has not been used
            // for a while, for example on this form:

            myPlayer.CursorHide.Add(this);

            // You can add as many "cursor hiding" forms to the player as you like, for example forms
            // that contain a display clone of the player or even forms that are not directly related
            // to the player.

            // If you want to be notified when the mouse cursor is hidden or shown by the player, you can
            // subscribe to the "Player.Events.MediaCursorHideChanged" event (see eventhandler below):

            myPlayer.Events.MediaCursorHideChanged += MyPlayer_MediaCursorHideChanged;

        }

        // Show display overlay at start up
        private void Form1_Shown(object sender, System.EventArgs e)
        {
            // show the display overlay at the start of the application (even if no movie is playing):
            // this instruction is put here because the player's display has to be 'created and visible'
            // to show the overlay:
            myPlayer.Overlay.Hold = true;
        }

        // Clean up - this is moved here from the 'Form1.Designer.cs' file and appended:
        protected override void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                isDisposed = true;
                if (disposing)
                {
                    // disposing a player also stops its overlay, display clones, eventhandlers etc.
                    myPlayer.Dispose();         // stop and dispose the player
                    myOverlay.Dispose();        // dispose the display overlay
                    myOpenFileDlg.Dispose();    // dipose the file selector
                    myInfoLabel.Dispose();      // dipose the info label

                    // used by the designer - clean up:
                    if (components != null) components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        // Dispose a taginfo
        private void DisposeTagInfo()
        {
            if (tagInfo != null)
            {
                myOverlay.subtitlesLabel.Text = string.Empty;
                panel1.BackgroundImage = null;
                tagInfo.Dispose(); // this also disposes the image (used with panel1.BackgroundImage)
                tagInfo = null;
            }
        }

        #endregion

        // **** Media Play / Pause - Resume / Stop ****************************************************

        #region Media Play / Pause - Resume / Stop

        private void PlayMedia()
        {
            if (myOpenFileDlg.ShowDialog() == DialogResult.OK)
            {
                myPlayer.Play(myOpenFileDlg.FileName);
                if (myPlayer.LastError)
                {
                    MessageBox.Show(myPlayer.LastErrorString);
                }
                else
                {
                    // Show media tag information (for audio media only)
                    if (!myPlayer.HasVideo)
                    {
                        tagInfo = myPlayer.Media.GetTagInfo();
                        panel1.BackgroundImageLayout = ImageLayout.Zoom;

                        panel1.BackgroundImage = tagInfo.Image;
                        myOverlay.subtitlesLabel.Text = tagInfo.Artist + "\r\n" + tagInfo.Title;
                    }
                }
            }
        }

        private void PauseMedia()
        {
            myPlayer.Paused = !myPlayer.Paused;
            if (myPlayer.Paused) button2.Text = "Resume";
            else button2.Text = "Pause";
        }

        private void StopMedia()
        {
            myPlayer.Stop();
        }

        #endregion

        // **** Player Eventhandlers ******************************************************************

        #region Player Eventhandlers

        // Show changed audio volume value
        private void MyPlayer_MediaAudioVolumeChanged(object sender, System.EventArgs e)
        {
            label3.Text = myPlayer.Audio.Volume.ToString();
        }

        // Show changed audio balance value
        private void MyPlayer_MediaAudioBalanceChanged(object sender, System.EventArgs e)
        {
            label4.Text = myPlayer.Audio.Balance.ToString();
        }

        // Display the elapsed and remaining playback time
        private void MyPlayer_MediaPositionChanged(object sender, PositionEventArgs e)
        {
            label1.Text = e.FromStart.ToString().Substring(0, 8); // "hh:mm:ss"
            label2.Text = e.ToStop.ToString().Substring(0, 8);    // "hh:mm:ss"

            // from .NET 4.0 TimeSpan supports (custom) format strings e.g.
            // label1.Text = e.FromStart.ToString(@"hh\:mm\:ss"); // "hh:mm:ss"
        }

        // Handle media audio output levels - calculate the values and paint the level displays
        private void MyPlayer_MediaPeakLevelChanged(object sender, PeakLevelEventArgs e)
        {
            // you could add some 'logic' here to make the movements of the indicators less 'jumpy'

            if (e.MasterPeakValue == -1) // media playback has stopped
            {
                // graphical presentation:
                leftLevel = rightLevel = 0;

                // value display:
                label5.Text = "0.00"; // same format as below
                label6.Text = "0.00";
            }
            else
            {
                // check e.ChannelCount for more than 2 (= stereo) channels
                // if you want to display the peak levels of all audio channels

                // graphical presentation:
                leftLevel = (int)(e.ChannelsValues[0] * levelUnit);
                rightLevel = (int)(e.ChannelsValues[1] * levelUnit);

                // value display (use string format because of float rounding errors - zero can become a small value):
                label5.Text = e.ChannelsValues[0].ToString("0.00");
                label6.Text = e.ChannelsValues[1].ToString("0.00");
            }
            panel4.Invalidate();
            panel5.Invalidate();
        }

        // Paint the left channel audio output level display
        private void Panel4_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle(Brushes.LightSlateGray, 0, 0, leftLevel, panel4.ClientRectangle.Height);
        }

        // Paint the right channel audio output level display
        private void Panel5_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle(Brushes.LightSlateGray, 0, 0, rightLevel, panel5.ClientRectangle.Height);
        }

        // Mouse clicked on player display - movie, overlay or just display
        private void MyPlayer_MediaMouseClick(object sender, MediaMouseEventArgs e)
        {
            //MessageBox.Show(e.Button.ToString() + " mouse button clicked on player display.", "PVS.AVPlayer How To...", MessageBoxButtons.OK, MessageBoxIcon.Information);
            if (myPlayer.Display.Mode == DisplayMode.Stretch) myPlayer.Display.Mode = DisplayMode.ZoomCenter;
            else myPlayer.Display.Mode = DisplayMode.Stretch;
        }

        // Mouse clicked on player display clone
        private void Clone_MouseClick(object sender, MouseEventArgs e)
        {
            //MessageBox.Show(e.Button.ToString() + " mouse button clicked on player display clone.", "PVS.AVPlayer How To...", MessageBoxButtons.OK, MessageBoxIcon.Information);
            if (myPlayer.DisplayClones.GetLayout((Panel)sender) == CloneLayout.Stretch) myPlayer.DisplayClones.SetLayout((Panel)sender, CloneLayout.Zoom);
            else myPlayer.DisplayClones.SetLayout((Panel)sender, CloneLayout.Stretch);
        }

        // Media has finished or stopped playing (1)
        private void MyPlayer_MediaEndedNotice(object sender, EndedEventArgs e)
        {
            // you can just stop any processes (and not starting new media) from the
            // MediaEndedNotice eventhandler that is fired just before the MediaEnded event.

            //switch (e.StopReason)
            //{
            //    case StopReason.Finished:
            //        break;

            //    case StopReason.AutoStop:
            //        break;

            //    case StopReason.UserStop:
            //        break;
            //}
        }

        // Media has finished or stopped playing (2)
        private void MyPlayer_MediaEnded(object sender, EndedEventArgs e)
        {
            DisposeTagInfo();

            //switch (e.StopReason)
            //{
            //    case StopReason.Finished:
            //        // play next media ...
            //        break;

            //    case StopReason.AutoStop:
            //        break;

            //    case StopReason.UserStop:
            //        break;
            //}
        }

        // Get media subtitles / media subtitle has changed
        private void MyPlayer_MediaSubtitleChanged(object sender, SubtitleEventArgs e)
        {
            // In this example the subtitle's text is shown in a label on a display overlay
            myOverlay.subtitlesLabel.Text = e.Subtitle;
        }

        // Show an info label on the position slider of the player when scrolled
        private void TrackBar1_Scroll(object sender, System.EventArgs e)
        {
            // Get the position slider's x-coordinate of the current position (= thumb location)
            // (myInfoLabel.AlignOffset has been set to 0, 7)
            Point myInfoLabelLocation = myPlayer.Sliders.ValueToPoint(trackBar1, trackBar1.Value);

            // Show the infolabel
            myInfoLabel.Show(myPlayer.Position.FromStart.ToString().Substring(0, 8), trackBar1, myInfoLabelLocation);
        }

        // Show an info label on the audio volume slider of the player when scrolled
        private void TrackBar2_Scroll(object sender, System.EventArgs e)
        {
            // Get the audio volume slider's x-coordinate of the current volume (= thumb location)
            // (myInfoLabel.AlignOffset has been set to 0, 7)
            Point myInfoLabelLocation = myPlayer.Sliders.ValueToPoint(trackBar2, trackBar2.Value);

            // Show the infolabel
            myInfoLabel.Show("Volume: " + ((float)myPlayer.Audio.Volume / 100).ToString("0.0"), trackBar2, myInfoLabelLocation);
        }

        // Show an info label on the audio balance slider of the player when scrolled
        private void TrackBar3_Scroll(object sender, System.EventArgs e)
        {
            // Get the audio balance slider's x-coordinate of the current balance (= thumb location)
            // (myInfoLabel.AlignOffset has been set to 0, 7)
            Point myInfoLabelLocation = myPlayer.Sliders.ValueToPoint(trackBar3, trackBar3.Value);

            // Calculate balance display value
            float val = (float)(myPlayer.Audio.Balance - 500) / 50;

            // Set the text for the info label (using StringBuilder)
            myInfoLabelText.Length = 0;
            if (val == 0) myInfoLabelText.Append("Balance: Center");
            else
            {
                if (val < 0) myInfoLabelText.Append("Balance: Left ").Append((-val).ToString("0.0"));
                else myInfoLabelText.Append("Balance: Right ").Append((val).ToString("0.0"));
            }

            // Show the info label
            myInfoLabel.Show(myInfoLabelText.ToString(), trackBar3, myInfoLabelLocation);
        }

        // The mouse cursor is hidden or shown by the player
        private void MyPlayer_MediaCursorHideChanged(object sender, CursorHideEventArgs e)
        {
            if (e.Visible) panel6.BackColor = Color.Lime;   // the cursor is shown
            else panel6.BackColor = Color.Red;              // the cursor is hidden
        }

        #endregion

        // **** Controls Handling *********************************************************************

        #region CheckBoxes

        // Set player display overlay
        private void CheckBox1_CheckedChanged(object sender, System.EventArgs e)
        {
            if (checkBox1.Checked) myPlayer.Overlay.Window = myOverlay;
            else myPlayer.Overlay.Window = null;
        }

        // Set player display clones overlay
        private void CheckBox2_CheckedChanged(object sender, System.EventArgs e)
        {
            myPlayer.DisplayClones.ShowOverlay = checkBox2.Checked;
        }

        // Set position slider live update
        private void CheckBox3_CheckedChanged(object sender, System.EventArgs e)
        {
            myPlayer.Sliders.PositionLiveUpdate = checkBox3.Checked;
        }

        // Set taskbar progress indicator
        private void TaskbarBox_CheckedChanged(object sender, System.EventArgs e)
        {
            if (taskbarBox.Checked) myPlayer.TaskbarProgress.Add(this);
            else myPlayer.TaskbarProgress.Remove(this);
        }

        // Set display shape - using the preset display shapes
        private void CheckBox4_CheckedChanged(object sender, System.EventArgs e)
        {
            if (++shapeStatus > 5) shapeStatus = 0;

            switch (shapeStatus)
            {
                case 1: // oval shaped video and overlay
                    myPlayer.Display.SetShape(DisplayShape.Oval, true, true);
                    panel2.BackColor = this.BackColor;
                    panel3.BackColor = this.BackColor;
                    break;

                case 3: // rounded rectangle shaped video and overlay
                    myPlayer.Display.SetShape(DisplayShape.Rounded, true, true);
                    panel2.BackColor = this.BackColor;
                    panel3.BackColor = this.BackColor;
                    break;

                case 5: // star shaped video and overlay
                    myPlayer.Display.SetShape(DisplayShape.Star, true, true);
                    panel2.BackColor = this.BackColor;
                    panel3.BackColor = this.BackColor;
                    break;

                default:
                    // normal shaped display and overlay
                    myPlayer.Display.SetShape(DisplayShape.Normal);
                    panel2.BackColor = Color.FromArgb(32, 32, 32);
                    panel3.BackColor = Color.FromArgb(32, 32, 32);
                    break;
            }
        }

        #endregion

        #region Buttons

        // Play
        private void Button1_Click(object sender, System.EventArgs e)
        {
            PlayMedia();
        }

        // Pause / Resume
        private void Button2_Click(object sender, System.EventArgs e)
        {
            PauseMedia();
        }

        // Stop
        private void Button3_Click(object sender, System.EventArgs e)
        {
            StopMedia();
        }

        // Quit
        private void Button5_Click(object sender, System.EventArgs e)
        {
            Application.Exit();
        }

        #endregion

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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

Share

About the Author

Peter Vegter
United States United States
No Biography provided

You may also be interested in...

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190306.1 | Last Updated 7 Aug 2018
Article Copyright 2010 by Peter Vegter
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid