Playing AVI Files using DirectX 9 with C# and .NET
Posted by Digital Angel Master on 1월 28, 2008

Figure 1 – Kangaroo Hopping Movie
Introduction
Just got back from a three week trip to Australia and all I can say is, “Give me a home among the gum trees.” (Australian programmers will get what I’m saying here.). Most people know what a kangaroo looks like, but most haven’t seen one up close. Needless to say, they are strange creatures if you are coming from the New York City. Unfortunately, the AVI kangaroo video taken by the digital camera was too large to upload to the site due to the size of the file. In any case, some of you are probably asking yourselves, “Kangaroos or not, how exactly do I play an AVI file in .NET?”. This article will show you how by demonstrating the implementation of a WinForm Video Player.
The Player
The Video Player takes advantage of the DirectX AudioVideoPlayback library. This library mindlessly allows you to play videos inside a Video object. The methods of the Video class are very straight forward (e.g. Play, Stop, Pause) and you simply construct the video object with the name of the file (e.g. “roo.avi”). The tables below illustrate some important methods and properties of the Video class.
| Method | Description |
| Open(string filename) | Opens an avi file with the passed parameter path name |
| Play | Plays the video |
| Stop | Stops the video |
| Pause | Pauses the video |
| SeekCurrentPosition(double time, SeekPositionFlags) | Moves to a particular time position in the avi file relative to the SeekPositionFlag. Time is in 1 x 10-7 seconds (or 0.1 microseconds) |
| StopWhenReady | Waits for the video object to be ready for stopping, and stops the video |
| Property | Type | Description |
| Owner | System.Windows.Forms.Control | Sets The Window Forms Control that contains the video. |
| Fullscreen | bool | Sets whether or not the video is shown fullscreen |
| Size | Size | Sets the size of the video |
| Duration | double | Gets the time (in seconds) of the full video |
| CurrentPosition | double | Sets the position of the video |
| Audio | Microsoft.DirectX.AudioVideoPlayback.Audio | Audio object allows you to control things like the volume, balance and playing of the sound in the video |
Coding
You must have DirectX 9 SDK installed to use the avi playing feature described in this article. You can get this SDK from the Microsoft MSDN site. (Note: It may require an MSDN subscription to get the full SDK, but the redistributable that runs the video is a free download). Once you have the DirectX SDK installed, you can include the Microsoft.DirectX.AudioVideoPlayback assembly as a reference to your project. Just right click on your project References in the Solution Explorer and add the reference as shown below. (If this reference isn’t in the .NET assembly list, you probably don’t have the DirectX 9 SDK installed):

Figure 2 – Adding the DirectX AudioVideoPlayback Reference
Now you just need to add the using statement in your Form to begin using the Video class:
using Microsoft.DirectX.AudioVideoPlayback;
So now let’s take a look at the implementation of the Video Class. The first step is to construct a Video object with the name of the video file which we retrieve from a OpenFile dialog. We then assign the Video.Owner property to the panel inside our winform. Also we resize the video to fit the original dimensions of the panel. Finally we quickly play and pause the video, in order to see the first frame.
/// <summary>
/// opens a video from an avi file
/// and plays the first frame inside the panel
/// </summary>
void OpenVideo()
{
openFileDialog1.InitialDirectory = Application.StartupPath;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// open the video
// remember the original dimensions of the panel
int height = videoPanel.Height;
int width = videoPanel.Width;
// dispose of the old video to clean up resources
if (_video != null)
{
_video.Dispose();
}
// open a new video
_video = new Video(openFileDialog1.FileName);
// assign the win form control that will contain the video
_video.Owner = videoPanel;
// resize to fit in the panel
videoPanel.Width = width;
videoPanel.Height = height;
// play the first frame of the video so we can identify it
_video.Play();
_video.Pause();
}
// enable video buttons
ControlLogic();
}
That’s really all there is to using the video object. If we want to play the video until the end, we simply call the Play method on the video object .
/// <summary>
/// Plays the video
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnPlay_Click(object sender, System.EventArgs e)
{
if (_video != null)
{
_video.Play();
}
}
Conclusion
The Video class in the Microsoft.DirectX.AudioVideoPlayback library is a powerful graphics class with a very simple implementation. Using this class, you can create powerful applications that include your favorite movie clips in the common avi format. I suspect it will play other movie formats as well (such as mpeg), however, I haven’t tried it. Good luck with this powerful multimedia tool and using it to see sharp videos.
Alexander said
Nice. Diden’t know it was so easy to create a Video Player. Just downloaded the Direct X SDK ;)
You just don’t tell what I should take from the toolbox to create the plaing window.
But ill try, maby im lucky ;)
Alexander.
Digital Angel Master said
Oh, great alexander, this solution was posted in codeproject.
if you wanna know more easy how to, visit http://www.codeproject.com
many c#.net resource in there.
Thank you for visit my blog :)
Good luck
Alexander said
Thanks for the fast feedback ;)
Ill post back and let you know how im going… ;)
Alexander
Alexander said
Could you please write the exact URL to the topic at the homepage please. Getting bit lost trying to find a example.
Can’t make it working. Always helps understanding when you get the whole projekt :D
Here comes the problem.
Video newVideo = new Video(“C:\\MyCoolVideo.avi”);
The compiler says nothing to this. But if I run the program, and I use this code, it stops the application saying something about a ‘LoaderLock’.
LeaderLock was detected
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.
a said
I think you nalso need to add a reference to DirectPlay ang DirectSound. Thi will solve the issue…
Digital Angel Master said
alexander, how about install direct-x sdk?
directx sdk now can download at http://www.microsoft.com
omg, i cannot find the article also.
I will test and feedback today. sorry :(
if are you using server edition now, change boot.ini setting first.
Digital Angel Master said
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.DirectX.AudioVideoPlayback;
namespace playvideo
{
///
/// Summary description for Form1.
///
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Panel panel1;
///
/// Required designer variable.
///
private System.ComponentModel.Container components = null;
private Microsoft.DirectX.AudioVideoPlayback.Video _video;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
///
/// Clean up any resources being used.
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///
/// Required method for Designer support – do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// panel1
//
this.panel1.Location = new System.Drawing.Point(8, 8);
this.panel1.Name = “panel1″;
this.panel1.TabIndex = 0;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.panel1);
this.Name = “Form1″;
this.Text = “Video Player Example”;
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
// open the video
// remember the original dimensions of the panel
int height = panel1.Height;
int width = panel1.Width;
// dispose of the old video to clean up resources
if (_video != null)
{
_video.Dispose();
}
// open a new video
_video = new Video(“test.avi”);
// assign the win form control that will contain the video
_video.Owner = panel1;
// resize to fit in the panel
panel1.Width = width;
panel1.Height = height;
// play the first frame of the video so we can identify it
_video.Play();
}
}
}
like this :)
Dagon^ said
Hey dude.
Nice code but I get the same LoaderLock message as Alexander. I use the exact same SDK as you but still get the error message.
Please get back as soon as you know something.
Thanks in advance.
Digital Angel Master said
How’bout release mode?
If you can modify boot.ini, do that first.
Ricky said
If i want to deploy my application that use this control i need to install the sdk on all the machine? Is there a light weight way?
Digital Angel Master said
Ricky,
No need distribute SDK to client.
that program is using DirectX Runtime only.
you can find the document of distribution in MSDN and http://download.microsoft.com
Ricky said
SDk size is the same of the runtime :(
Digital Angel Master said
no way.
SDK imports runtime.
in Download center, SDK was over then 300MB
sehresh said
Hello
can you plz tell me the exact link from where i can download the activeX SDk……..
plz tell me…..i really need. i m not getting in msdn site
Digital Angel Master said
here it is.
http://www.microsoft.com/downloads/details.aspx?FamilyID=5493f76a-6d37-478d-ba17-28b1cca4865a&DisplayLang=en
Alessandro said
Hi, nice tutorial. I have a qestion. How can I set to fullscreen with a double click on videoPanel?
Digital Angel Master said
it can control from event.
in designer dialog, usually right panel, you can find some “Thunder” icon.
when “mouse over” when “mouse out” like that events can be control.
you can double click to event contents, visual studio will give you “to do”.
> video1.FullScreen(); <
put only this code. that’s all.
Alessandro said
I have already tryed it…
This is the code:
private void panel2_DoubleClick(object sender, EventArgs e)
{
MessageBox.Show(“Test”);
}
If there is no video, I can see the messagebox. When a video starts and making a double click on panel, the megebox don’t appear.
I tryed to create a eventhandler on _video.owner, I get the same situation…
Dusan said
Hey m8, did anyone have solution for that?
thanks
Dusan said
edit: I found solution :D
what i did is, i set mouse down event, and used e.Clicks, it works same as doubleclick
void Owner_MouseDown(object sender, MouseEventArgs e)
{
if (e.Clicks == 2)
{
_video.Fullscreen = !_video.Fullscreen;
}
}
I hope it helps, i know i had a lot of trouble to make that.
Vincent said
I tried to use your solution for detecting a mouse click in the video but it doesn’t work. If I set the mouse down event and i click on the video the event doesn’t raise.
Any help?
Thank you
rspercy58 said
Alexander, the LoaderLock exception can be turned off. Click Debug, then Exceptions, then Managed Debugging Assistants. Scroll down till you see LoaderLock, Uncheck it.
This is a By Project Only check.
I made a AVI player that is error free. If you would like a copy w/full code, e-mail me at rspercy58@comcast.net and I’ll send you a copy.
I based my player on this same concept, but I got the same code from c-sharp corner. The guy that posted it is the owner of the site. Is this you?
Regards
theodora said
hello nice program…i made my own project using directX in order to play sounds like this
filepath = My.Application.Info.DirectoryPath
filepath = filepath.Substring(0, filepath.Length – 9)
Dim MySound1 As New Microsoft.DirectX.AudioVideoPlayback.Audio(filepath & “sounds\Am.wav”)
MySound1.Play()
the program works fine but when i publish it the sounds wont play because of some problems with directX
i know that the problem is that in project properties–>publish–>Application files where Microsoft.DirectX.AudioVideoPlayback.dll
Microsoft.DirectX.Direct3D.dll
Microsoft.DirectX.dll
are not in the download group but i don’t know what to do ….please help me…
thanks in advance…sorry for my english
theodora
tibs said
I use visual c# 2005. does this code works with it?
using Microsoft.DirectX.AudioVideoPlayback;
So now let’s take a look at the implementation of the Video Class. The first step is to construct a Video object with the name of the video file which we retrieve from a OpenFile dialog. We then assign the Video.Owner property to the panel inside our winform. Also we resize the video to fit the original dimensions of the panel. Finally we quickly play and pause the video, in order to see the first frame.
///
/// opens a video from an avi file
/// and plays the first frame inside the panel
///
void OpenVideo()
{
openFileDialog1.InitialDirectory = Application.StartupPath;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// open the video
// remember the original dimensions of the panel
int height = videoPanel.Height;
int width = videoPanel.Width;
// dispose of the old video to clean up resources
if (_video != null)
{
_video.Dispose();
}
// open a new video
_video = new Video(openFileDialog1.FileName);
// assign the win form control that will contain the video
_video.Owner = videoPanel;
// resize to fit in the panel
videoPanel.Width = width;
videoPanel.Height = height;
// play the first frame of the video so we can identify it
_video.Play();
_video.Pause();
}
// enable video buttons
ControlLogic();
}
That’s really all there is to using the video object. If we want to play the video until the end, we simply call the Play method on the video object .
///
/// Plays the video
///
///
///
private void btnPlay_Click(object sender, System.EventArgs e)
{
if (_video != null)
{
_video.Play();
}
}
fatih said
I want to play automatically 3 avi videos which are called v1.avi, v2.avi, v3.avi, but I want to send send (1) to D1, D2, D3 pins of the parallel port when first (v1.avi) video is playing at the end, and second video is playing at the end and the last one… respectively, Can you help me about it?
Digital Angel Master said
Tail to nose :D
sara said
i read ur artile ,which is very good well done .
thank u for publishing it,however i have a problem,LoaderLock message i tried the solution u said that to uncheck the loader i did it but still got another error
it says error in application in the bellow line:
_video = new Video(openFileDialog1.FileName);
please advice me to run it ,iam in ergent need for my gratuate project.
thank u
Digital Angel Master said
compile with release mode :D
maybe almost loaderlock will be solved with that.
TAN TH said
how do we repeat the video? that is, when it has reached the end, I want to start all over again.
thanks