Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
LeftbarAd
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » DirectX » Playing AVI Files using DirectX 9 with C# and .NET

Playing AVI Files using DirectX 9 with C# and .NET

Ever wonder how to play videos in .NET? This article will show you how to use the managed DirectX 9 Video class to play avi video files.

Author Rank:
Technologies: Windows Forms,Visual C# .NET
Total downloads : 5868
Total page views :  160907
Rating :
 4.75/5
This article has been rated :  20 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
AVIPlayer.ZIP
 
ArticleAd
Become a Sponsor



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.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
AVIPlayer.ZIP
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Nice articleMahesh11/30/2005
Nice article Mike. Hope you enjoyed Ausie vacation.
Reply | Email | Delete | Modify | 
 
 
Re: Nice articleWu4/7/2007
After running the row '_video = new Video(openFileDialog1.FileName)',the value of _video is still null.Why?

Hope this help,thank you!

Reply | Email | Delete | Modify | 
 
Re: Re: Nice articleRobert4/25/2007
I'm getting the same problem with null!
Reply | Email | Delete | Modify | 
 
Re: Re: Nice articleShafqat5/21/2007

sir,

plz send me solution of the problem._video=null

Reply | Email | Delete | Modify | 
MDAs!!Ozz12/17/2005

I think, i can help,

From the Debug menue, find the exceptions,

The under Managed exception, Remove the LoaderLock exception, this will prevent that exception...

 

Hope this help

Reply | Email | Delete | Modify | 
is it possible to record?francis12/30/2005

nice article.....but i have a question.

Does this applicable to recording videos??

If yes, can give sample code???

~Thank You~

Reply | Email | Delete | Modify | 
Help Me ... F1 i want a country code filesMona12/31/2005

Hello;

After reading your article about playing AVI using c#.net and DX9.

I want to know if there are any calsses or dlls using c#.net and DX9 (direct show) help me to "convert videos from any codec format to MPEG1 and MPEG2 formats?!!!"

waiting from you reply because i got sick searching about that topic.

thanks alot for your help.

Reply | Email | Delete | Modify | 
'System.Security.SecurityException'kit4/13/2006

if i build the solution and run on my computer (with Microsoft Visual Studio 2005 + DirectX 9 SDK installed), the application is running fine. however, if i run on other computers (without Microsoft Visual Studio 2005 + DirectX 9 SDK installed), there is a lot of error. for the DirectX 9 issue, i think i already fixed it by setting the DirectX Reference's 'Copy Local' to True. however, there is another error

'An unhandled exception of type 'System.Security.SecurityException' occurred in mscorlib.dll

Additional information: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.'

could anyone help?

 

Reply | Email | Delete | Modify | 
 
 
Re: 'System.Security.SecurityException'Sergio3/12/2008
Hello i´m Sergio, i have a question concerned to the library of DirectX SDK to make a player, Did you solve the problem with Security.Sy