Click here to Skip to main content
14,027,283 members
Click here to Skip to main content

Stats

747.4K views
30.2K 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 System;
using System.Drawing;
using System.Windows.Forms;
using PVS.AVPlayer;
using System.Drawing.Drawing2D;
using System.Text;

#endregion

namespace AVPlayerExample
{
    public partial class SoundPlayer : Form
    {
        /*
        
        SoundPlayer - the playback part of the Sound Recorder,
        using a PVS.AVPlayer Player.
        
        */

        // ******************************** Fields

        #region Fields

        private const int       WINDOW_HEIGHT_SMALL = 88;               // used with show sliders
        private const int       WINDOW_HEIGHT_LARGE = 140;
        private const double    PEAK_UNITS          = 51.0 / 32767.0;   // width of peak panel / max value peak level

        // Form
        private MainWindow      _baseForm;
        private Font            _crystalFont20;

        // Player
        private Player          _soundPlayer;
        private bool            _countDown;

        // Mediafile
        internal bool           UseLastRecording    = true;
        internal string         PlayFile            = string.Empty; // file to play - selected (with 'Open') or last recording

        // Peak Level
        private bool            _hasLevelMeterEvents;
        private float           _leftLevel;
        private float           _rightLevel;
        private SolidBrush      _levelMeterBrush;

        // Sliders infolabel
        private InfoLabel       _infoLabel;
        private StringBuilder   _infoLabelText      = new StringBuilder(64);

        // Miscellaneous
        private bool            _showSliders        = true;
        private bool            _disposed;

        #endregion

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

        #region Main

        public SoundPlayer(MainWindow baseForm)
        {
            InitializeComponent();

            _baseForm = baseForm;
            Owner = _baseForm;

            _crystalFont20 = new Font(_baseForm.FontCollection.Families[0], 20, FontStyle.Italic);

            _levelMeterBrush = new SolidBrush(MainWindow.Prefs.SoundLevelMeterColor);

            playCounterLabel.Font = _crystalFont20;
            playCounterLabel.UseCompatibleTextRendering = true;

            // create an 'hidden display' (plays video sound only)
            Panel hiddenDisplay = new Panel { Bounds = new Rectangle(-20, -20, 16, 16) };
            Controls.Add(hiddenDisplay);

            _soundPlayer = new Player();
            _soundPlayer.Sliders.AudioVolume = volumeSlider;
            _soundPlayer.Sliders.AudioBalance = balanceSlider;
            _soundPlayer.Sliders.Position = positionSlider;
            _soundPlayer.Display.Window = hiddenDisplay;

            //_soundPlayer.MediaPositionChanged += _soundPlayer_MediaPositionChanged; - see SoundPlayer_VisibleChanged
            _soundPlayer.Events.MediaStarted += _soundPlayer_MediaPlayingChanged;
            _soundPlayer.Events.MediaEnded += _soundPlayer_MediaPlayingChanged;

            //  - see SoundPlayer_VisibleChanged
            //_soundPlayer.MediaPeakLevelChanged += _soundPlayer_MediaPeakLevelChanged;
            //_hasPeakLevelEvents = !_soundPlayer.LastError; // returns error if Stereo Mix not available

            _infoLabel                  = new InfoLabel();
            _infoLabel.RoundedCorners   = true;
            _infoLabel.ForeColor        = Color.FromArgb(189, 159, 87);
            _infoLabel.Text             = "Ty";   // 'pre-size' height for brush size
            _infoLabel.BackBrush = new LinearGradientBrush(
                new Rectangle(new Point(0, 0), _infoLabel.Size),
                Color.FromArgb(80, 80, 80), Color.Black, LinearGradientMode.Vertical);
            _infoLabel.AlignOffset      = new Point(0, -1);
            _infoLabel.Duration         = 500;

            volumeSlider.Scroll         += VolumeSlider_Scroll;
            balanceSlider.Scroll        += BalanceSlider_Scroll;
            positionSlider.Scroll       += PositionSlider_Scroll;
        }

        // no need to update position and peak level display when hidden or closed
        private void SoundPlayer_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                _soundPlayer.Events.MediaPositionChanged += _soundPlayer_MediaPositionChanged;
                if (!_hasLevelMeterEvents)
                {
                    _soundPlayer.Events.MediaPeakLevelChanged += _soundPlayer_MediaPeakLevelChanged;
                    _hasLevelMeterEvents = !_soundPlayer.LastError;
                }
            }
            else
            {
                _soundPlayer.Events.MediaPositionChanged -= _soundPlayer_MediaPositionChanged;
                if (_hasLevelMeterEvents)
                {
                    _soundPlayer.Events.MediaPeakLevelChanged -= _soundPlayer_MediaPeakLevelChanged;
                    _hasLevelMeterEvents = false;
                }
            }
        }

        protected override bool ShowWithoutActivation
        {
            get { return true; }
        }

        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_soundPlayer.Paused) ButtonFlash.Remove(pauseButton);

                    if (_hasLevelMeterEvents)
                    {
                        _soundPlayer.Events.MediaPeakLevelChanged -= _soundPlayer_MediaPeakLevelChanged;
                        _hasLevelMeterEvents = false;
                    }

                    _soundPlayer.Dispose(); _soundPlayer = null;
                    _crystalFont20.Dispose(); _crystalFont20 = null;

                    _levelMeterBrush.Dispose(); _levelMeterBrush = null;

                    if (_infoLabel != null) _infoLabel.Dispose();

                    if (components != null) components.Dispose();
                }
                _disposed = true;
            }
            base.Dispose(disposing);
        }

        #endregion

        // ******************************** Player Event Handling

        #region Player Event Handling

        void _soundPlayer_MediaPositionChanged(object sender, PositionEventArgs e)
        {
            playCounterLabel.Text = _countDown ? e.ToEnd.ToString().Substring(0, 8) : e.FromStart.ToString().Substring(0, 8);
        }

        // Update interface with media playing / non playing
        void _soundPlayer_MediaPlayingChanged(object sender, EventArgs e)
        {
            playLight.LightOn = _soundPlayer.Playing;
        }

        private void _soundPlayer_MediaPeakLevelChanged(object sender, PeakLevelEventArgs e)
        {
            _leftLevel = e.ChannelsValues[0];
            _rightLevel = e.ChannelsValues[1];

            leftPeakPanel.Invalidate();
            rightPeakPanel.Invalidate();
        }

        // Selected a new Output Level Device
        private void _soundPlayer_MediaLevelDeviceChanged(object sender, EventArgs e)
        {
            // (re) set eventhandlers
            _soundPlayer.Events.MediaPeakLevelChanged -= _soundPlayer_MediaPeakLevelChanged;
            _soundPlayer.Events.MediaPeakLevelChanged += _soundPlayer_MediaPeakLevelChanged;
            _hasLevelMeterEvents = !_soundPlayer.LastError;
        }

        private void VolumeSlider_Scroll(object sender, EventArgs e)
        {
            // Get the audio volume slider's x-coordinate of the current volume (= thumb location)
            Point location = SliderValue.ToPoint(volumeSlider, volumeSlider.Value);
            location.Y += 10; // adjust y-location

            // Show the infolabel
            _infoLabel.Show("Volume: " + ((float)_soundPlayer.Audio.Volume / 100).ToString("0.0"), volumeSlider, location);
        }

        private void BalanceSlider_Scroll(object sender, EventArgs e)
        {
            // Get the audio balance slider's x-coordinate of the current balance (= thumb location)
            Point location = SliderValue.ToPoint(balanceSlider, balanceSlider.Value);
            location.Y += 10; // adjust y-location

            // Get adjusted balance value
            float val = (float)(_soundPlayer.Audio.Balance - 500) / 50;

            // Adjust the displayed text
            _infoLabelText.Length = 0;
            if (val == 0) _infoLabelText.Append("Balance: Center");
            else
            {
                if (val < 0) _infoLabelText.Append("Balance: Left ").Append((-val).ToString("0.0"));
                else _infoLabelText.Append("Balance: Right ").Append((val).ToString("0.0"));
            }

            // Show the infolabel
            _infoLabel.Show(_infoLabelText.ToString(), balanceSlider, location);
        }

        private void PositionSlider_Scroll(object sender, EventArgs e)
        {
            // Get the position slider's x-coordinate of the current position (= thumb location)
            Point location = SliderValue.ToPoint(positionSlider, positionSlider.Value);

            // Show the infolabel
            TimeSpan time = _soundPlayer.Position.FromStart;
            _infoLabel.Show(
                string.Format("{0:00;00}:{1:00;00}:{2:00;00}", time.Hours, time.Minutes, time.Seconds),
                positionSlider, location);
        }

        #endregion

        // ******************************** Drag Borderless Form

        #region Drag Borderless Form

        private const int WM_NCLBUTTONDOWN = 0xA1;
        private const int HT_CAPTION = 0x2;
        private void Control_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                //this.Cursor = Cursors.SizeAll;
                ((Control)sender).Capture = false;
                Message msg = Message.Create(Handle, WM_NCLBUTTONDOWN, (IntPtr)HT_CAPTION, IntPtr.Zero);
                base.WndProc(ref msg);
                //this.Cursor = Cursors.Default;
            }
        }

        #endregion

        // ******************************** Level Meter Display

        #region Level Meter Display

        private void LeftLevelMeterPanel_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle(_levelMeterBrush, 0, 0, _leftLevel * leftPeakPanel.ClientRectangle.Width, leftPeakPanel.ClientRectangle.Height);
        }

        private void RightLevelMeterPanel_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle(_levelMeterBrush, 0, 0, _rightLevel * rightPeakPanel.ClientRectangle.Width, rightPeakPanel.ClientRectangle.Height);
        }

        private void LevelMeterPanel_Click(object sender, EventArgs e)
        {
            SetLevelMeterColor();
        }

        private void SetLevelMeterColor()
        {
            ColorDialog dlg = new ColorDialog();
            dlg.Color = _levelMeterBrush.Color;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                _levelMeterBrush.Color = dlg.Color;
                MainWindow.Prefs.SoundLevelMeterColor = dlg.Color;
            }
            dlg.Dispose();
        }

        #endregion


        // ******************************** Play Media

        #region Play Media

        private void PlayMedia()
        {
            if (PlayFile == string.Empty) SelectMedia();

            if (PlayFile != string.Empty)
            {
                _soundPlayer.Play(PlayFile);
                if (_soundPlayer.LastError)
                {
                    ShowErrorMessage();
                    PlayFile = string.Empty;
                }
            }
        }

        internal void ClosePlayer()
        {
            _soundPlayer.Stop();
            if (_soundPlayer.Paused) pauseButton.PerformClick();
            _soundPlayer.Repeat = repeatMenuItem.Checked = false;
            UseLastRecording = lastRecordingMenuItem.Checked = true;
            PlayFile = string.Empty;
        }

        #endregion


        // ******************************** Main Menu

        #region Main Menu

        private void OpenMenuItem_Click(object sender, EventArgs e)
        {
            if (SelectMedia()) PlayMedia();
        }

        private void LastRecordingMenuItem_Click(object sender, EventArgs e)
        {
            UseLastRecording = lastRecordingMenuItem.Checked = !UseLastRecording;
        }

        private void CountdownTimerMenuItem_Click(object sender, EventArgs e)
        {
            _countDown = countdownTimerMenuItem.Checked = !_countDown;
        }

        private void RepeatMenuItem_Click(object sender, EventArgs e)
        {
            _soundPlayer.Repeat = repeatMenuItem.Checked = !_soundPlayer.Repeat;
        }

        private void ShowSlidersMenuItem_Click(object sender, EventArgs e)
        {
            _showSliders = !_showSliders;
            showSlidersMenuItem.Checked = _showSliders;

            if (_showSliders)
            {
                volumeSlider.Visible = true;
                _soundPlayer.Sliders.AudioVolume = volumeSlider;

                balanceSlider.Visible = true;
                _soundPlayer.Sliders.AudioBalance = balanceSlider;

                positionSlider.Visible = true;
                _soundPlayer.Sliders.Position = positionSlider;

                playerPanel.Height = Height = WINDOW_HEIGHT_LARGE;
            }
            else
            {
                playerPanel.Height = Height = WINDOW_HEIGHT_SMALL;

                volumeSlider.Visible = false;
                _soundPlayer.Sliders.AudioVolume = null;

                balanceSlider.Visible = false;
                _soundPlayer.Sliders.AudioBalance = null;

                positionSlider.Visible = false;
                _soundPlayer.Sliders.Position = null;
            }
        }

        private void CloseMenuItem_Click(object sender, EventArgs e)
        {
            ClosePlayer();
            Hide();

            _baseForm.SetRecorderMenuItems();
        }

        #endregion

        // ******************************** Volume and Balance Menus

        #region Volume and Balance Menus

        private void MuteMenuItem_Click(object sender, EventArgs e)
        {
            _soundPlayer.Audio.Volume = 0;
        }

        private void AverageVolumeMenuItem_Click(object sender, EventArgs e)
        {
            _soundPlayer.Audio.Volume = 500;
        }

        private void MaximumVolumeMenuItem_Click(object sender, EventArgs e)
        {
            _soundPlayer.Audio.Volume = 1000;
        }

        private void LeftBalanceMenuItem_Click(object sender, EventArgs e)
        {
            _soundPlayer.Audio.Balance = 0;
        }

        private void CenterBalanceMenuItem_Click(object sender, EventArgs e)
        {
            _soundPlayer.Audio.Balance = 500;
        }

        private void RightBalanceMenuItem_Click(object sender, EventArgs e)
        {
            _soundPlayer.Audio.Balance = 1000;
        }

        #endregion

        // ******************************** Play, Pause and Stop Buttons

        #region Play, Pause and Stop Buttons

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

        private void PauseButton_Click(object sender, EventArgs e)
        {
            _soundPlayer.Paused = !_soundPlayer.Paused;
            if (_soundPlayer.Paused) ButtonFlash.Add(pauseButton, pauseButton.ForeColor, Color.Black);
            else ButtonFlash.Remove(pauseButton);
        }

        private void StopButton_Click(object sender, EventArgs e)
        {
            _soundPlayer.Stop();
        }

        #endregion

        // ******************************** Select Media OpenFileDialog

        #region Select Media OpenFileDialog

        private bool SelectMedia()
        {
            bool result = false;

            OpenFileDialog dlg = new OpenFileDialog
            {
                Title = "Open Sound Recording",
                Filter = "Sound Recordings (*.wav)|*.wav|All Files (*.*)|*.*",
                CheckFileExists = true
            };

            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                // TODO check for .ppl for playlist mode
                PlayFile = dlg.FileName;
                result = true;
            }
            dlg.Dispose();
            return result;
        }

        #endregion

        // ******************************** Error Message Dialog

        #region Error Message Dialog

        private void ShowErrorMessage()
        {
            ErrorDialog errorDialog = new ErrorDialog(MainWindow.APPLICATION_NAME, "SOUND PLAYER\r\n\r\n" + _soundPlayer.LastErrorString, false);

            errorDialog.checkBox1.Hide();
            errorDialog.checkBox2.Hide();

            _baseForm.CenterDialog(this, errorDialog);
            errorDialog.ShowDialog();

            errorDialog.Dispose();
        }

        #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.190419.4 | Last Updated 7 Aug 2018
Article Copyright 2010 by Peter Vegter
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid