Use Visual C # To develop a media player

Source: Internet
Author: User

Abstract:Learn how to use the DirectShow control in Microsoft Visual C #. NET and develop a media player. Follow the procedure described in this article to create a simple Visual C # application for playing digital audio and video.

   Introduction

Microsoft Visual C # is the most popular programming language in the world, using the latest version of Visual C #.. NET, you can quickly and effectively develop applications based on Windows Forms, or embed Microsoft Windows Media? Player 9 Series ActiveX controls add new, interesting, and useful functions to applications.

The DirectShow control is a standard ActiveX control that provides a large number of functions. The DirectShow control provides the following functions:

· Advanced playback of digital media files and streaming media.

· Use the playlist function.
· Playback of DVDs and CDs.
· Access the Media Library in Windows Media Player ).
· Metadata processing function.
· Supports subtitles.
· Supports audio in multiple languages.
· Control network connectivity and access statistics.

Next, let's take a look at the goal of constructing this Media Player. Once the goal is determined, the amount of code and the complexity of the program are determined. In this article, media players must achieve the following goals:

· It is a simple AWT application driven by menus.
· Contains a "file" menu. the File menu contains three menu items:
· "Open" is used to open a media file.
· "Loop" indicates whether to play the video once (default) or repeatedly.
· "Exit" and exit the program.
· It can run on multiple platforms.
· Core functions are implemented through the JMF (Java Media Framework) API.

Follow the steps described in this article to create a basic application based on Windows Forms and embed the Player control in it. The example application you created has the following features:

· Create an instance of the DirectShow control.
· The main interoperability assembly of Windows Media Player provides the Component Object Model (COM) interoperability.
· Allows users to open and play Windows Media files, especially files with the extension. wma or. wmv.
· Create a transfer control button for users to play, pause, and stop digital media content.
· Display the title of the current digital media file.
· Demonstrate how to use the Player object model, including examples of using attributes, methods, and events.

My program only tells you how to use DirectShow to make a player in C,

In this program, we need to solve some minor problems:

1. How to open a media file from your disk

2. How to enable or disable the buttons on the toolbar

3. How to set the display text of the status bar

4. How to control the time

5. How to use time control events
 
6. How to Use DirectShow to play media files

7. How to Determine the playback status...

Displays the application you want to create, where a digital audio file named "Melow" is being played and visualized.


Figure 1
· This article assumes that you already have some knowledge about the integrated development environment of Visual C # and Visual Studio. NET.

Preparations

Before creating an application, you need to install necessary software and register the primary interoperability assembly (QuartzTypeLib ).

Here is a brief introduction to the DirectShow interface:

We need to use the DirectShow component provided by DiectX to play the video screen and audio files. you can use this interface to conveniently play shared images and sound files. all you need to do is install the DirectShow interface, use its functions, and configure the correct interface parameters.

Unfortunately,. NET does not officially support DirectX. Yes, maybe you heard that DirectX9 supports it, right? Yes, but we haven't gotten the best results since the final version was finalized. But in any case, do we still need to use it? Otherwise this article has to be voided. Yes, maybe you have used VB. Right, that's it. We just need to use it.

  Start Project

After installing necessary software and registering QuartzTypeLib, you can start Visual C # And start creating a project for the sample application. Next I will introduce the operation steps of this process.

  Create a project

To create an empty project, follow these steps:

1. Start Visual Studio. NET and click New Project ).

2. in the Visual C # Projects (Visual C # project) folder, click Windows Application, type the name of the new project (preferably DirectShow), and click OK ).

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

3. This name does not have any special significance or use. Therefore, change the form name to frmPlayMedia in the Properties window and the form text to "media player ".

Add a reference to DirectShow in the project

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

1. Open the Visual Studio toolbox and click Components to display the panel.

2. Right-click the Panel and click Customize Toolbox to display the dialog box.

3. On the COM Components (COM component) tab, select Interop. QuartzTypeLib. dll. (If Interop. QuartzTypeLib. dll is not listed for some reason, Click Browse [Browse] and find the file QuartzTypeLib. dll .)

4. Click OK to close the dialog box.


Figure 2
To use DirectShow in 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 Options statements (not used in this project) and before all other code. After the statement is added.

Develop applications

After creating a Player control instance connected to the Framework through PIA, you can add other elements to the form and write the code to complete the actual operation.
Add Windows Forms Control

1. in the View menu, click Designer or click View Designer in Solution Explorer to switch to Form Designer.

2. Add a file, playback, and information menu to the form.

3. In the Windows Forms Panel of the toolbox, add a toolbar, a status bar, and an image imageList to your form.

4. In the Properties window, change the toolbar name to toolBar1 and add four Buttons on Buttons. Change the status bar name to statusBar1 and add three panels respectively.

5. On the panel of the toolbox, add a panel version panel1.

6. Add a timer timer1.

7. Adjust the layout of controls in the form to meet your needs and facilitate your use. Is the form layout completed in Visual Studio Designer.


Figure 3
  Write code

How to open the media file you want?

The first step is to write the code to open the Windows Media File in frmPlayMedia. To automatically switch to the Code view and edit the Code of the Click event handler (menuItem2_Click) that opens the menu, double-Click the "toolbar" button on the form. Add the following code to the event handler:

Remember, "file-> open..." Yes, almost everyone using windows will do this. How can this be done?

Let's take a 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 easy, 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. Explains how it works.

DirectShow provides the most basic services for multimedia stream playback. These multimedia streams can be local files or transmitted by servers. In particular, DirectShow supports video playback and supports compressing video content in different file and stream formats, including Windows Media, MPEG, AVI, and WAV.

At the core of DirectShow, a service is a modular set of components, called a filter, which can be arranged into a filter Chart Based on the media type. Filters can operate on data streams, such as reading, analyzing, decoding, formatting, or rendering.

Filters are arranged in a tree. This tree is called a Filter tree and is managed by the Filter Graph Manager (FGM. The FGM application can indirectly control the filter tree by using the Microsoft Windows Media Player control, and directly control the tree by calling the COM interface. The DirectShow filter tree (see Figure 1) consists of a directed filter sequence from the source to the target Renderer, all connected through the input and output filter pins. Filter pins negotiate which media types they will support. Multi-media data streams between FGM Control tree filters. Because DirectShow has a flexible and reconfigurable filter tree architecture, DirectShow supports playback and shunting of multiple media types using the same software components. Developers can also compile their own filters to expand DirectShow multimedia support.

  Filter

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

Obtain source information (for example, obtain a Media Stream)
Analysis (for example, reading, splitting, and formatting packets on a stream)
Conversion (for example, decoding WMA and MPEG-4 audio and video streams)
Rendering (for example, generating audio PCM or video RGB/YUV output when appropriate, and passing data to DirectSound and DirectDraw)

Filters use several types of interfaces, such as pins, counters, transmitter, and clock interfaces, to execute their tasks. Filters implement and open many interfaces. FGM can use these interfaces to create, connect, and control trees. Filters often implement the IBaseFilter interface that includes the following methods:

Filter status: Run, stop, and pause.
Restore the filter and vendor information.
Obtain and set the reference clock.
Restores the filter status information.
Enumerative filter leads.
Position pin when rebuilding the filter tree

When you click open, this code displays a dialog box for you to browse on your computer and select the. wma or. wmv file to play. When you select a file (and click OK), the Code sets the URL attribute of Player as the selected file. Because the Player autoStart attribute is set to True by default, the Player immediately opens and plays the Selected digital media file.

Next, add the code for the play/pause button. In the code window, Click in the stop or pause menu, and then Click in the method name list. Add the following code to the Click event handler created for you by Visual C:

Let's 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_objvideowindoincluowner = (int) panel1.Handle;
M_objvideow.windowstyle = WS_CHILD | WS_CLIPCHILDREN;
M_objvideow.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.setpolicywindow (int) this. Handle, WM_GRAPHNOTIFY, 0 );
M_objMediaPosition = m_objFilterGraph as IMediaPosition;
M_objMediaControl = m_objFilterGraph as IMediaControl;

//

How to play, pause, and stop?
Simply read these functions.
//

M_objMediaControl.Run (); // playback
M_objMediaControl.Pause (); // pause
M_objMediaControl.Stop (); // stop

// This code is very simple. When you click the play/pause button, the code checks the playState attribute of the Player. If the Player is playing a digital media file, the code will pause the file. If the Player has been paused or stopped, the code will start the Player again.
OK. Let's see how we control the time progress?
//

Private void timerjavastick (object sender, System. EventArgs e)
{
If (m_CurrentStatus = MediaStatus. Running)
{
UpdateStatusBar ();
}
}
See the UpdateStatusBar () above. Here, the status bar is updated not once every Ms.

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 ";
}
}
Another question is how can the program know that it has finished playing?

This will be a little troublesome. Think about the solution? By the way, windows is message-driven. Find out what messages are there. Some are EC_COMPLETE. Do you still remember "WndProc? Yes, my old friend. This time we have to rewrite it to capture the EC_COMPLETE message. This message is the parent form of DirectShow notification, and the playback is complete.

Protected override void WndProc (ref Message m)
{
If (m. Msg = wm_graphpolicy)
{
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 ();
Updatemedilbar ();
}
}
Catch (Exception)
{
Break;
}
}
}
Base. WndProc (ref m );
}
The above code runs as long as the playback status changes. If the Player is playing (the Player is playing when the user opens the file, because autoStart is set to True), the Code enables the play/pause button and stop button for the user to perform operations. Then, the code changes the text of the play/pause button to "pause", so that you can use this button to pause the playing process. Finally, the Code retrieves the title of the current digital media file and updates the text of the title label to display the title.

If the Player is paused (you click the play/pause button), the code changes the text of the play/pause button to "play", prompting you to use this 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 ".

Everything is over. Now we have to do something to find a film to enjoy our achievements.

After the code of the sample project is compiled, you can generate and run the solution.

  Generate a solution

Click Build Solution in the Build menu ). Visual Studio starts compiling and generates a project. If all the entered content is correct, the generation process is successfully completed without any errors. If an error is reported, check your code and correct the error.

Use sample applications

To run a project in the debugger, press F5 on the disk. If the "view generated code" topic shows unprocessed exceptions, stop the debugging session, delete or comment out the corresponding lines in the generated code, and then press F5.

You can click open to find the. wma or. wmv file. (the file type depends on the file type you selected in the open dialog box ). Select a file and click "OK". The "open" dialog box is closed to start playing the digital media file. The status of the transfer control button also changes. In this case, you can use the transfer control button to pause, start again, or stop playback completely.

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.