How to Play Video/Audio in C#.NET WinForms- Video Player in C#.NET

This project is about playing Video/Audio files into your C#.NET Window Application. In this project I will tell you to develop a Video Player in C#.NET. The Video Player has features of Play, Pause, Stop Video/Audio and Forward/Backward Functionality and you can set the Volume of the currently running Video/Audio Files. I have also attached a demo project that can be download for free. Also I want to tell you one important thing about playing Video/Audio in C#.NET that to play Video/Audio files you must add  “Microsoft.DirectX” and “Microsoft.DirectX.AudioVideoPlayBack” dll into your project’s References Folder.




Free Download

Video Player in C#.NET : Demo Project

 DirectX 9.0 Web Setup: Free Download




Controls and Properties 

To develop a Video Player I have used the Following controls in the
WinForm.
a. Panel: id="Panel1", BackColor="Black".
b. Button: id="btnUpload".
c. Button: id="btnPlay".
d. Button: id="btnStop".
e. TrackBar: id="vdoTrackBar".
f. TrackBar: id="VolumeTrackBar".
g. OpenFileDialog: name="openFileDialog1".
h. Timer: name="Timer1", Interval="1000".
i. TextBox: id="txtStatus".

NameSpace:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX.AudioVideoPlayback;

Global Variables:
Video vdo;
public string mode="play";
public string PlayingPosition, Duration;

Code Page:

1. Download the DirectX Web Setup and add “Microsoft.DirectX” and “Microsoft.DirectX.AudioVideoPlayBack”

dll into your project’s References Folder :

DirectX 9.0 Web Setup: Free Download
2. Initialize Form:
public Form1()
        {
            InitializeComponent();
            VolumeTrackBar.Value = 4;
        }
3. Browse a video/audio file:
private void btnupload_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.ShowDialog();
            openFileDialog1.Title = "Select video file..";
            openFileDialog1.InitialDirectory = Application.StartupPath;
            openFileDialog1.DefaultExt = ".avi";
            openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
            vdo = new Video(openFileDialog.FileName);

            vdo.Owner = panel1;
            panel1.Width = 700;
            panel1.Height = 390;
            Duration = CalculateTime(vdo.Duration);
            PlayingPosition = "0:00:00";
            txtStatus.Text = PlayingPosition + "/" + Duration;

            vdoTrackBar.Minimum = 0;
            vdoTrackBar.Maximum = Convert.ToInt32(vdo.Duration);

        }
4. Play/Pause The Selected Video/Audio :
private void btnPlay_Click(object sender, EventArgs e)
        {

            if (vdo != null)
            {
                if (vdo.Playing)
                {
                    vdo.Pause();
                    timer1.Stop();
                    btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
                }
                else
                {
                    vdo.Play();
                    timer1.Start();

                    btnPlay.BackgroundImage = Play_Video.Properties.Resources.pause;
                }
            }

        }
5. Stop selected Video/Audio :
private void btnStop_Click(object sender, EventArgs e)
        {
            vdo.Stop();
            btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
            vdoTrackBar.Value = 0;
        }
6. Control Video/Audio Seek Bar to Forward/Backward :
private void vdoTrackBar_Scroll(object sender, EventArgs e)
        {
            if (vdo != null)
            {
                vdo.CurrentPosition = vdoTrackBar.Value;
            }
        }
7. Control Video/Audio Volume Bar :
private void VolumeTrackBar_Scroll(object sender, EventArgs e)
        {
            if (vdo != null)
            {
                vdo.Audio.Volume = CalculateVolume();
            }
        }
        public int CalculateVolume()
        {
          switch (VolumeTrackBar.Value)
            {
                case 1:
                    return -1500;
                case 2:
                    return -1000;
                case 3:
                    return -700;
                case 4:
                    return -600;
                case 5:
                    return -500;
                case 6:
                    return -400;
                case 7:
                    return -300;
                case 8:
                    return -200;
                case 9:
                    return -100;
                case 10:
                    return 0;
                default:
                    return -10000;
            }
        }
8. Timer_Tick() Event :
private void timer1_Tick(object sender, EventArgs e)
        {

            PlayingPosition = CalculateTime(vdo.CurrentPosition);
            txtStatus.Text = PlayingPosition + "/" + Duration;

            if (vdo.CurrentPosition == vdo.Duration)
            {
                timer1.Stop();
                Duration = CalculateTime(vdo.Duration);
                PlayingPosition = "0:00:00";
                txtStatus.Text = PlayingPosition + "/" + Duration;
                vdo.Stop();
                btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
                vdoTrackBar.Value = 0;
            }
            else
                vdoTrackBar.Value += 1;

        }

I am Samith Jhon a content writer and a Professional Blogger.  Certified with CompTIA LX0-101 Exam test questions  which is very popular these days and have a great scope in the field of IT Certification. I always like to take certification Exam test questions and now I have planned to pass CompTIA SG0-001 Exam test questions. These kinds of Exam test questions could secure your future as well as your job.

admin (158 Posts)


Comments ( 25 )

  1. HariKrishnanAugust 22, 2011 16 // Reply

    I tried the code above;but unfortunately i get an error while trying to browse the file (it was a file with ex: of ".avi") "DLL 'C:\WINDOWS\assembly\GAC\Microsoft.DirectX\1.0.2902.0__31bf3856ad364e35\Microsoft.DirectX.dll' is attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang." I couldn't find any remedy yet ..! can you please help me??

    • sourabhAugust 22, 2011 16 // Reply

      Hello Harikrishan, your code is giving error because you didnt added the dll "Microsoft.DirectX" in your references folder. Once you will add this dll then the code will run without any error

  2. dvdwholesale1August 23, 2011 16 // Reply

    p90 dvds p90x is an extremely intense program.Sheer will and determination may get you to the finish line,but to achieve the best results,you’ve got to have the proper quality and quantity of nutrition.We make these supplements optional,so you have a choice.But know that P90x supplements were designed for this program and will supply your body with the necessary nutrients to give you added strength energy,and stamina for each workout. As you may notice from the math on the following pages, p90 dvds p90x is not bulit around adaily “calorie deficit” for weight loss like the general Beachbody plans found in Power 90,Kathy Smits’s Project :You!Type 2,and Slimin 6.It’s important that you understand why ,so you have the right training mentality with this program ,with the right expectations.

  3. ArchanaAugust 23, 2011 16 // Reply

    Hi, Can we play files like DivX or mp3 without using VLC with this application? Kindly reply asap....

  4. sourabhAugust 23, 2011 16 // Reply

    Hello Archana, Surely you can run your videos(mp3 and all types of files) using this application...

  5. Jim BachJanuary 26, 2012 17 // Reply

    I am trying to develop using C# Express 2010 on Win7. I can not install the DirectX9 you point to, as Windows says I already have a newer version installed. When I try to code the "using Microsoft.DirectX..." statement C# complains that DirectX is not in the Microsoft namespace. Now what? Thanx.

    • wolfgangMarch 30, 2012 15 // Reply

      Jim, did you receive any answer or found a solution? I am still struggling the same problem... Cheers, Wolfgang.

    • SafdarSeptember 13, 2012 19 // Reply

      please add Microsoft.DirectX reference in reference folder,

      • SafdarSeptember 13, 2012 19 // Reply

        add Microsoft.DirectX.AudioVideoPlayback reference

  6. *******March 11, 2012 15 // Reply

    what problime with calculatetime ??? The name 'calculate' does not exist in the

  7. CHataBAsMarch 13, 2012 15 // Reply

    private void btnStop_Click(object sender, EventArgs e) { vdo.Stop(); >>>>>>>>>>>> timer1.Stop();<<<<<<<< btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay; vdoTrackBar.Value = 0; } hey add timer stop on stop button track bar still moving if u click stop:) i love your tutorial great respect:D

  8. DipaliOctober 3, 2012 16 // Reply

    how to apply swf button in asp.net using c#.

  9. JayshreeOctober 11, 2012 17 // Reply

    Hey Good Keep it up...

  10. JayshreeOctober 11, 2012 17 // Reply

    Actlly i wnt d code wh canvert MP3 audio file into Text plzzzzzzz anybady knw help m..Thnx in Advance

  11. nfl jerseysNovember 20, 2012 18 // Reply

    The post is written in very a good manner and it entails much useful information for me. I am happy to find your distinguished way of writing the post.

  12. ArgiankaDecember 19, 2012 18 // Reply

    where we should put the "global variables"?thanks

  13. ahmedFebruary 18, 2013 18 // Reply

    when press on browes button show message LoaderLock was detected Message: DLL Video\bin\Debug\Microsoft.DirectX.AudioVideoPlayback.dll' is attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang.

    • VincentFebruary 22, 2013 18 // Reply

      to resolve this error: Debug >> Exceptions >> Manage Debugging Assistants >> Uncheck LoaderLock

  14. ramkarthikFebruary 22, 2013 18 // Reply

    pls upload ur project with code.....

  15. ramkarthikFebruary 22, 2013 18 // Reply

    pls upload ur project solution with code.....in winrar file

  16. ZaidApril 13, 2013 15 // Reply

    when I click on browse following error was occurred FileLoadExpectation was unhandled Could not load file or assembly 'Microsoft.DirectX.AudioVideoPlayback.dll' or one of its dependencies. A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A) Please help me its urgent.... Thanks

  17. VilmaAugust 1, 2013 15 // Reply

    Simply desire to say your article is as astonishing. The clearness in your post is just cool and i can assume you are an expert on this subject. Well with your permission let me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please keep up the enjoyable work.

  18. Nuvagenic ReviewAugust 7, 2013 15 // Reply

    Hi there Dear, are you in fact visiting this site regularly, if so after that you will absolutely obtain good experience.

Leave a reply

Your email address will not be published.

Comment moderation is enabled. Your comment may take some time to appear.