Developing a media player with Visual C #

Source: Internet
Author: User
Tags filter exit contains include object model reference visual studio
Visual| Media Summary: Learn how to use the DirectShow control in Microsoft Visual C #. NET to develop a media player. Following the steps described in this article, you can create a simple Visual C # application to play digital audio and video.

  

Brief introduction

Microsoft Visual C # is the world's most popular programming language, using Visual C #. NET, the latest version of Visual C #, to quickly and efficiently develop windows-based applications, and to embed Microsoft windows Media? The Player 9 Series application of ActiveX controls adds fresh, interesting, and very useful features.

The DirectShow control is a standard ActiveX control that provides a great deal of functionality. The features provided by the DirectShow control include:

· Advanced playback capabilities for digital media files and streaming media.

· The ability to use playlists.
· The ability to play DVDs and CDs.
· Access the Media Library in Windows media Player.
· The ability to work with meta data.
· Supports subtitles.
· Supports audio in multiple languages.
· The function of controlling network connectivity and accessing relevant statistic information.

Let's take a look at what it takes to construct the media player and determine the target as well as the complexity of the code and the program. The media player in this article has to achieve the following goals:

· is a menu-driven simple AWT application.
· Contains a File menu that contains three menu items:
· Open to open the media file.
· Loop, is played once (the default), or repeatedly played.
· Exit, exit the program.
· Can be run on a variety of platforms.
· Core functionality is implemented through the JMF (Java Media Framework) API.

Following the steps in this article, you will create a basic Windows forms based application and embed the Player control in it. The sample application you create has the following characteristics:

· Creates an instance of the DirectShow control.
· Provides Component Object Model (COM) interoperability with the Windows Media Player Primary interop assembly.
· Allows users to open and play Windows Media files, especially files that have a. wma or. wmv file name extension.
· Creates a Transport control button for the user to play, pause, and stop digital media content.
· Displays the title of the current digital media file.
· Demonstrates how to use the Player object model, including examples of using properties, methods, and events.

My program just tells you how to use DirectShow to do a player in C #,

Some of the minor problems we have to address in this program are:

1. How to open a media file from your disk

2. How to enable and Disable buttons on the sidebar

3. How to set the status bar display text

4. How to control time

5. How to use the events of the Time control
 
6. How to use DirectShow to play media files

7. How to determine the playback status and so on ...

The following illustration shows the application you are about to create, which is playing a digital audio file named "Melow", with a visual effect.


Figure 1

· This article assumes that you already have some knowledge of Visual C # and Visual Studio.NET integrated development environments.
Preparatory work

Before you start creating your application, you need to install the necessary software and register the primary interop assembly (QuartzTypeLib).

Here is a brief introduction to the DirectShow interface:

Playing video and sound files we need to use the DirectShow component that DIECTX provides for us. Using this interface allows you to easily play those shared images and sound files. All you have to do is install the DirectShow interface and use its functional functions and configure the correct interface parameters.

Unfortunately, it's. NET does not officially support DirectX. Yes, well, maybe you heard about DirectX9 support, right? Yes, but we didn't get the best results on the day the final version was finalized. But we still need to use it anyway, right? or this article has to be voided. Yes, maybe you've used VB, right, That's it, that's what we're going to use.

Start Project

After you install the necessary software and register QuartzTypeLib, you can start Visual C # to start creating projects for the sample application. I'll show you how to do this procedure below.

Create a project

Follow these steps to create an empty project:

1. Start Visual Studio. NET, and then click New Project.

2. In the Visual C # Projects (Visual C # Project) folder, click Windows Application (Windows application), type a name for the new project (preferably DirectShow), and then click OK.

Visual C # uses the default Windows form "Form1" to create a new project.

3. This name has no particular meaning or usefulness, so change the form's name to Frmplaymedia in the Properties window, changing the form text to media Player.

To add a reference to DirectShow in a project

Follow these steps to add a reference to DirectShow in your project:

1. Open the Visual Studio Toolbox, and then click Components (Component) to display the panel.

2. Right-click the panel and click Customize Toolbox (custom Toolbox) to display the dialog box.

3. On the COM components (COM components) tab, select Interop.QuartzTypeLib.dll. (if Interop.QuartzTypeLib.dll is not listed for some reason, click Browse and look for a file named QuartzTypeLib.dll.) )

4. Click OK to close the dialog box.


Figure 2

To use DirectShow in your code, you need to add a line of code to reference the DirectShow namespace. At the top of the form code window, add the following code before all declaration statements:

Using QuartzTypeLib;

The using statement must be after all the Options statements (not used in this project), and before all other code. After you add the statement.
Developing applications

After creating an instance of the Player control that is connected to the Framework through the PIA, you can add the additional elements that you want to the form and write the code that completes the actual operation.
Add Windows Forms Control

1. On the View menu, click Designer (Designer), or click the View Designer button in Solution Explorer (Solution Explorer) to switch to the form designer.

2. Add a menu of files, playback, information, etc. on the form.

3. In the Windows Forms (Windows Forms) Panel of the Toolbox, add a toolbar, a status bar, and a picture ImageList to your form.

4. In the Properties window, change the name of the toolbar to toolBar1 and add 4 buttons to the buttons. The status bar name is changed to STATUSBAR1 and three panel is added respectively.

5. In the Toolbox panel, add a face version Panel1 to your form.

6. Add a timer timer1.

7. Adjust the way the controls are arranged in the form to suit your needs and make it easy for users to use. The following illustration is a completed form layout in the Visual Studio Designer (designer).


Figure 3

Writing code

How to open the media file you want?

The first step is to write the code that opens the Windows Media file in Frmplaymedia. To automatically switch to Code view and edit the codes for the Click event handler (Menuitem2_click) of the Open menu, double-click the toolbar button on the form. Add the following code to the event handler:

Do you remember "file-> open ..." Yes, almost everyone who uses Windows does this. How do I achieve this?

It's easy to look at the following code:

OpenFileDialog OpenFileDialog = new OpenFileDialog ();
Openfiledialog.filter = "Media files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3| All Files|*.* ";
if (DialogResult.OK = = Openfiledialog.showdialog ())
{
....
}

Look, it's simple, right? Remember to write a function to put it in. When you click the OK button, the DirectShow interface will get the file you want to play. The figure below explains how it works.

DirectShow provides the most basic service for multimedia streaming playback, which can be local files, and can be transmitted by the server. In particular, DirectShow can support video playback, compressing video content in different file and streaming formats, including Windows Media, MPEG, AVI, and WAV.

At the heart of DirectShow, a service is a modular set of components, called filters, that can be arranged into filter graphs according to media types. Filters can manipulate data streams, such as reading, parsing, decoding, formatting, or rendering.

Filters are arranged in a tree, called a filter tree, managed by the Filter Tree Manager (Filter Graph Manager, referred to as FGM). You can use the FGM application to control the filter tree indirectly by using the Microsoft Windows Media Player control, or you can control it directly by invoking the COM interface method. The DirectShow filter tree (see Figure 1) consists of a sequence of forward filters from the source to the target renderer, all connected by the input and output filter pins. The filter pins negotiate which media types they will support. FGM controls the multimedia data flow between the tree filters. Because DirectShow has a flexible, reconfigurable filter tree architecture, DirectShow can use the same software component to support playback and streaming of multiple media types. Developers can also extend DirectShow multimedia support by writing their own filters.

Filtering device

A filter is a registered DirectShow class that performs many media processing tasks. These tasks include:

Get source information (for example, get media streams)
Analysis (for example, performing packet read, detach, and format on a stream)
Transformations (e.g., decoding WMA and MPEG-4 audio and video streams)
Rendering (for example, generating audio PCM or video RGB/YUV output at the appropriate time, passing data to DirectSound and DirectDraw)

Filters use several types of interfaces, such as pins, counters, transporter, and clock interfaces, to perform their tasks. The filter implements and opens many interfaces. FGM can use these interfaces to create, connect, and control trees. Filters often implement Ibasefilter interfaces that contain the following methods:

Run, stop, and pause the filter state.
Recover filter and vendor information.
Get and set reference clock.
Restores filter state information.
Enumerates the filter leads.
Locating pins when rebuilding filter tree

When the user clicks Open, this code displays a dialog box for the user to browse on the computer and select the. wma or. wmv file to play. When the user selects a file (and clicks OK), the code sets the Player's URL property to the file selected by the user. Because the AutoStart property of the player is set to True by default, the player immediately opens and plays the user-selected digital media file.

Next, add the code for the Play/pause button. In the Code window, click in the Stop, Pause menu, and then click in the list of method names. Add the following code to the Click event handler that Visual C # created for you:

See how the following code is implemented:

CleanUp ();
M_objfiltergraph = new Filgraphmanager ();
M_objfiltergraph.renderfile (Openfiledialog.filename);
M_objbasicaudio = M_objfiltergraph as Ibasicaudio;
Try
{
M_objvideowindow = M_objfiltergraph as Ivideowindow;
M_objvideowindow.owner = (int) Panel1. Handle;
M_objvideowindow.windowstyle = Ws_child | Ws_clipchildren;
M_objvideowindow.setwindowposition (Panel1. Clientrectangle.left,
Panel1. Clientrectangle.top,
Panel1. Clientrectangle.width,
Panel1. Clientrectangle.height);
}
catch (Exception ex)
{
M_objvideowindow = null;
}
M_objmediaevent = M_objfiltergraph as imediaevent;
M_objmediaeventex = M_objfiltergraph as Imediaeventex;
M_objmediaeventex.setnotifywindow (int) this. Handle, wm_graphnotify, 0);
M_objmediaposition = M_objfiltergraph as imediaposition;
M_objmediacontrol = M_objfiltergraph as IMediaControl;

//

How to play, Pause, stop?
Simple These functions look literal also know.
//

M_objmediacontrol.run ()//Play
M_objmediacontrol.pause ()/Pause
M_objmediacontrol.stop ()/Stop

This code is very simple. When the user clicks the Play/pause button, the code checks the player's playstate properties. If the player is playing a digital media file, the code pauses the playback of the file, and if the player has paused or stopped, the code starts the player playback file again.
OK, how do we control the time schedule?
//

private void Timer1_Tick (object sender, System.EventArgs e)
{
if (M_currentstatus = = mediastatus.running)
{
Updatestatusbar ();
}
}

See the top of the Updatestatusbar (); This is to let it not 100ms update the status bar.

The code is as follows:

private void Updatestatusbar ()
{
Switch (m_currentstatus)
{
Case MediaStatus.None:statusBarPanel1.Text = "Stopped"; Break
Case MediaStatus.Paused:statusBarPanel1.Text = "paused"; Break
Case MediaStatus.Running:statusBarPanel1.Text = "Running"; Break
Case MediaStatus.Stopped:statusBarPanel1.Text = "Stopped"; Break
}
if (m_objmediaposition!= null)
{
int s = (int) m_objmediaposition.duration;
int h = s/3600;
int m = (S-(H * 3600))/60;
s = S-(h * 3600 + M * 60);
Statusbarpanel2.text = String.Format ("{0:d2}:{1:d2}:{2:d2}", H, M, s);
s = (int) m_objmediaposition.currentposition;
h = s/3600;
m = (S-(H * 3600))/60;
s = S-(h * 3600 + M * 60);
Statusbarpanel3.text = String.Format ("{0:d2}:{1:d2}:{2:d2}", H, M, s);
}
Else
{
Statusbarpanel2.text = "00:00:00";
Statusbarpanel3.text = "00:00:00";
}
}

There is also a problem program how can you know it is finished?

It's going to be a bit of a hassle. Yes, Windows is message driven. Then look for the news. Some are ec_complete. Do you remember "WndProc" it? Yes, my old friend, this time we have to rewrite it to capture the ec_complete message. This message is DirectShow notify the parent form, playback is over.

protected override void WndProc (ref message M)
{
if (m.msg = = wm_graphnotify)
{
int Leventcode;
int lParam1, LPARAM2;
while (true)
{
Try
{
M_objmediaeventex.getevent (out leventcode,out lparam1,out lparam2,0);
M_objmediaeventex.freeeventparams (Leventcode, lParam1, lParam2);
if (Leventcode = = Ec_complete)
{
M_objmediacontrol.stop ();
m_objmediaposition.currentposition = 0;
M_currentstatus = mediastatus.stopped;
Updatestatusbar ();
Updatetoolbar ();
}
}
catch (Exception)
{
Break
}
}
}
Base. WndProc (ref m);
}

As soon as the playback state changes, the code above will run. If the player is playing (when the user opens the file, and because AutoStart is set to True), the code enables the play/pause button and the Stop button for the user to perform the action. The code then changes the text of the Play/pause button to paused so that the user can use the button to pause the playback process. Finally, the code retrieves the title of the current digital media file and updates the text of the caption label to display the caption.

If the player is paused (the user clicks the Play/pause button), the code changes the text of the Play/pause button to play to prompt the user to use the button to resume playback.

If the player is stopped (the user clicks the Stop button), the code disables the Stop button (because the player has stopped working) and restores the text of the Play/pause button to the default value play.

It's all over, now it's time to do something to find a film and enjoy yourself.

After you have finished writing the code for the sample project, you can build and run the solution.

Build Solution

In the Build menu, click Build Solution (Generate solution). Visual Studio starts compiling and building the project. If you type everything correctly, the build process completes without any errors. If the build reports an error, check your code and correct the error.

Using the sample application

To run the project in the debugger, press the F5 key on your keyboard. If the unhandled exception that is described in the "View generated Code" topic appears, you should stop the debugging session, delete or comment out the corresponding line in the generated code, and then press the F5 key.

You can click Open to find the. wma or. wmv file (whichever file you choose depends on the type of file you selected in the Open dialog box). When you select a file and click OK, the Open dialog box closes, the digital media file begins to play, and the status of the Transfer control button changes. You can then use the Transfer control button to pause, restart, or completely stop playback.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.