Use Visual C # to develop a media player

xiaoxiao2021-03-06  42

Summary: How to use the DirectShow control in Microsoft Visual C # .NET, how to develop a media player. According to the steps introduced in this article, you can create a simple Visual C # app 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 #. Visual C # .NET, you can quickly and effectively develop Windows-based applications, or to embed Microsoft Windows Media? Player 9 Series The application of the ActiveX control adds fresh, interesting and very practical features.

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

· Advanced playback of digital media files and streaming media.

· Use the function of the playlist.

• Play the function of DVD and CD.

· Access Media Library in Windows Media Player.

· The function of processing metadata.

· Support subtitles.

· Supports audio in multiple languages.

· Control network connectivity and access to relevant statistics.

Let's take a look at what goals for constructing this media player to achieve the target, the goal is determined to determine the complexity of the code and the program. The media player of this article should achieve the following objectives:

· It is a menu-driven simple AWT application.

· Contains a "file" menu, the file menu contains three menu items:

· "Open" to open media files.

· "Circulation", is playing once (default) or repeats.

· "Exit" and exit the program.

· You can run on a variety of platforms.

· The core function is implemented through the JMF (Java Media Framework) API.

Based on the steps introduced in this article, you will create a basic application based on a Windows Form and embed the Player control. The sample application you created has the following features:

· Create an instance of the DirectShow control.

• Provide component object model (COM) interoperability using the Windows Media Player main interoperability assembly.

• Allow users to open and play the Windows Media file, especially file extension is .WMA or .wmv file.

· Create a transfer control button for users to play, suspend, and stop digital media content.

· Show the title of the current digital media file.

· Demonstrate how to use the Player object model, including examples of using properties, methods, and events.

My program just tells you how to make a player in C # in C #.

In this program we have to solve some small questions:

1. How to open media files from your disk

2. How to make the button on the toolbar and disable

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

4. How to control time

5. How to use time control events

6. How to use DirectShow to play media files

7. How to determine the play state, etc. ...

The figure below shows the application you will create, where you are playing a digital audio file called "melow", and presenting a visual effect.

figure 1

· This article assumes that you have certain Visual C # and Visual Studio.net integrate development environment knowledge.

Preparation Before you start creating an application, you need to install the necessary software and register the primary interoperable assembly (Quartztypelib).

Here you briefly introduce the DirectShow interface:

Play the video and sound files We have to use DIECTX to provide the DirectShow component. Using this interface allows you to easily play the shared images and sound files. You have to do just just install the DirectShow interface and use its function function and Configure the correct interface parameters. Unfortunately, .NET does not officially support DirectX. Yes Maybe you heard that DirectX9 support is it? Yes, but in the final version of the day, we haven't come to the most Good effect. But no matter what we still want to use? Don't be invalidated. Yes, maybe you have used VB, right, it is it, we are using it.

Start project

After installing the necessary software and registering QuartzTypelib, you can start Visual C # and start to create a project for the sample application. Below I will introduce you to this process.

Create a project

Create an empty items as follows:

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

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

Visual C # creates a new project using the default Windows Form "Form1".

3. This name does not have a special meaning or use, so please change the form name to FRMPLAYMEDIA in the Properties window, change the form text to "Media Player".

Add reference to DirectShow in your 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 on the panel, then click Customize Toolbox, and the dialog is displayed.

3. On the Com Components tab, select Interop.quartzTypelib.dll. (If Interop.quartzTypelib.dll is not listed for some reason, click Browse [Browse] and find files named quartztypelib.dll.)

4. Click OK to close the dialog.

figure 2

To use DirectShow in your code, you will need to add a line of code to reference the DirectShow namespace. In the top of the form code window, add the following code to 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 adding this statement.

Developing applications Create a PLAYER control instance connected to the Framework, you can add the other elements you need to your form and write code that completes the actual operation.

Add a Windows Form Control

1. In the View menu, click the Designer, or click the View Designer button in the Solution Explorer (Solution Explorer) to switch to the Form Designer.

2. Add menu such as files, play, and information on the form.

3. In the Windows Forms panel of the Toolbox, add a toolbar, a status bar, and image ImageList for your form, a status bar, and image IMAGELIST. 4. In the Properties window, change the name of the toolbar to Toolbar1, add 4 buttons on Buttons. The name of the status bar is changed to STATUSBAR1 and add three PANELs separately.

5. In the panel of the toolbox, add a panel PANEL1 for your form.

6. Add a timer Timer1.

7. Adjust the arrangement of the control in the form to make it in line with your needs and make it easy for users. The following figure shows the form layout completed in the Visual Studio Designer (Designer).

image 3

Write code

How to open you want the media file?

The first step is to write the code that opens the Windows Media file in FRMPlayMedia. To automatically switch to the Code view and edit 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:

Remember? "Document -> Open ..." Yes, almost every person using Windows will operate this way. How to implement?

Take a look at the code below:

OpenFiledialog OpenFiledialog = New OpenFiledialog (); OpenFiledialog.Filter = "Media Files | * .mpg; *. Avi; *. WMA; *. MOV; *. WAV; *. MP2; *. MP3 | All Files | *. *. "; if (DialogResult.ok == OpenFiledialog.Showdialog ()) {....

It's very simple to see it? Remember to write a function put it in. When you click on 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 services for multimedia stream playback, which can be a local file, or the server is transmitted. In particular, DirectShow can support video playback, supports compressed video content in different files and stream formats, including Windows Media, MPEG, AVI, and WAV.

At the core of DirectShow, the service is a modular set of components, called a filter, which can be arranged in a filter diagram according to the media type. Filters can operate data streams such as read, analysis, decoding, formatting, or rendering.

The filter is arranged in a tree, which is called a filter tree, which is managed by Filter Graph Manager, referred to as FGM. With the FGM application, you can directly control the filter tree by using the Microsoft Windows Media Player control, and can also be directly controlled by calling the COM interface method. DirectShow Filter Tree (see Figure 1) consists of a source to the target renderer, all of which are connected by an input and output filter pin. Filter pin negotiations which media types will be supported. The FGM controls the multimedia data stream between the tree filter. Because DirectShow has a flexible, reconfigurable filter tree architecture, DirectSHOW can support multiple media types of playback and splitting using the same software ingredients. Developers can also extend DirectShow multimedia support by writing their own filters.

filter

The filter is a registered DirectShow class, which performs many media information processing tasks. These tasks include:

Get source information (for example, obtaining media flow)

Analysis (for example, executing package, separation, and formatting)

Transformation (eg, decoding WMA and MPEG-4 audio and video stream) rendering (for example, generating audio PCM or video RGB / YUV output when appropriate, transfer data to DirectSound and DirectDraw)

The filter uses several types of interfaces such as pins, counters, transmitters, and clock interfaces to perform their tasks. Filters achieve and open many interfaces. FGM can use these interfaces to create, connect, and control the tree. The filter often implements the IBaseFilter interface containing the following methods:

Run, stop and suspend the filter status.

Restore filter and manufacturers information.

Get and set the reference clock.

Restore the filter status information.

Enumerate filter leads.

Relocating filter tree positioning pin

When the user clicks "Open", this code will display a dialog for users to browse on the computer and select .WMA or .wmv files to play. When the user selects the file (and click "OK"), the code sets the Player's URL property to the user selected file. Since Player's AutoStart attribute is set to True by default, Player opens and plays the digital media file selected by the user.

Next, add the code of the play / pause button. In the code window, click, and then click Click in the Method Name list. Add the following code to Visual C # In the Click event handler you created:

See how the code below 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, look at these functions simply too literal? Know ./m_objmediacontrol.run ();// Play m_objmediacontrol.pause (); // Pause m_objmediacontrol.stop (); // Stop // This code is very simple. When the user clicks on the play / pause button, the code will check the PlayState property of the Player. If Player is playing a digital media file, the code will pause the file playback; if the Player has paused or stopped, the code starts the Player playback file again. OK, in order to control how time progress? // private sender Here is to let it don't have 100ms to update the status bar.

code show as below:

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";}} How can I know how it is played?

This will be a bit trouble, think about what way? Yes, Windows is a message-driven. So what news is found. Some of the EC_COMPLETE. Remember "WNDPROC" it? Yes, my old friend, this time we have to override it to capture the EC_COMPLETE message. This message is DirectShow to inform the parent form, and the play 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 long as the playback status changes, the above code will run. If Player is playing (when the user opens the file, it is played. Because AutoStart is set to true), the code will enable the play / pause button and the stop button so that the user performs operations. After that, the code changes the text of the play / pause button to "Pause" 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 title tag to display the title.

If Player is paused (the user clicks the play / pause button), the code will change the text of the play / pause button to "Play" to prompt the user to recover playback.

If Player is stopped (the user clicks the stop button), the code will disable the stop button (because Player has stopped working) and the text of the play / pause button is "play".

Everything is over, now I have to do something to find a movie to enjoy my own results.

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

Solution

Click Build Solution in the Build (Generated) menu. Visual Studio began to compile and generate projects. If you type all the content is correct, the generation process will be successfully completed, and no errors will occur. If you generate a report error, check your code and correct the error.

Use the sample application

To run the project in the debugger, press the F5 key on the keyboard. If there is an unprocessed exception introduced in the "View Generated Code" topic, the debug session should be stopped, delete or comment out the corresponding row in the generated code, and then press the F5 key.

You can click "Open" to find .WMA or .wmv files (where to choose from, depending on the file type you selected in the "Open" dialog). After selecting a file and click "OK", the "Open" dialog is turned off, starting to play a digital media file, and the status of the transfer control button also changes. At this point you can use the Transmission Control button to pause, restart or stop playback.

转载请注明原文地址:https://www.9cbs.com/read-74308.html

New Post(0)