Share via


Playing Digital Media in a Visual Basic .NET Application

by Jim Travis

Microsoft Corporation

November 2003

Applies to:

Microsoft® Windows Media® Player 9 Series
Microsoft Visual Basic® .NET
Microsoft .NET Framework
Microsoft ActiveX® controls

Summary: This article provides information about using the Microsoft Windows Media Player 9 Series ActiveX control with Microsoft Visual Basic .NET 2002 or Visual Basic .NET 2003. By following the steps in the article, you can create a simple Visual Basic-based application that plays digital audio and video.

Contents

  • Introduction
  • Getting Ready
  • Starting the Project
  • Developing the Application
  • Building the Solution
  • Using IntelliSense with the Player Control
  • For More Information

Introduction

Microsoft® Visual Basic® is the most popular programming language in the world. With Visual Basic .NET 2003, the latest version of Visual Basic, you can develop Windows® Forms-based applications quickly and effectively. You can add even more exciting, fun, and useful features to the applications you create by embedding the Microsoft Windows Media® Player 9 Series ActiveX® control.

The techniques described in this article also work when using Visual Basic .NET 2002. However, in some instances the code you need to use is different. This will be pointed out to you when appropriate.

The Windows Media Player 9 Series ActiveX control is a standard ActiveX control that provides a range of functionality that you can use. Features available with the Player control include:

  • High-level playback functionality for digital media files and streaming media.
  • Features for working with playlists.
  • Playback functionality for DVDs and CDs.
  • Access to the Media Library in Windows Media Player.
  • Features for working with metadata.
  • Support for closed captioning.
  • Support for multiple audio languages.
  • Features for controlling network connectivity and accessing related statistics.

This article takes you through the steps for creating a basic Windows Forms-based application that embeds the Player control. The sample application you create will:

  • Create an instance of the Windows Media Player 9 Series ActiveX control.
  • Provide Component Object Model (COM) interoperability by using the Windows Media Player primary interoperability assembly.
  • Allow the user to open and play Windows Media files; in particular, files having a .wma or .wmv file name extension.
  • Create transport control buttons that enable the user 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 properties, methods, and events.

The following diagram shows the application you will create, which is playing a digital audio file named "Mellow" and displaying a visualization.

Sample Player application playing audio

Figure 1. Sample Player application playing audio

This article assumes you have some knowledge of Visual Basic and of using the Visual Studio® integrated development environment.

Getting Ready

Before you begin creating your application, you need to install the necessary software and register the Primary Interop Assembly (PIA).

Install the software

To create the sample application described in this article, you'll need the following software:

  • Microsoft Visual Basic .NET 2003 (or 2002) and the Windows .NET Framework Software Development Kit (SDK). Visual Basic .NET is the language you use to create the sample application; .NET Framework is the integral Windows component that Visual Basic .NET-based applications run on. Typically, the program and SDK install as a package, so when you install Visual Basic .NET or Visual Studio .NET, you receive the Windows .NET Framework SDK at the same time.
  • Windows Media Player 9 Series. The Windows Media Player ActiveX control installs with the Player, so you need to install the Player first. Windows Media Player 9 Series is the only version that supports the usage described in this article. You can install the Player from the Microsoft Web site.
  • Windows Media Player 9 Series SDK. You also need to install the full Player SDK package, which includes important reference documentation about the Player control, sample code, and utilities. It also includes the Windows Media Player primary interop assembly (PIA), which is a redistributable file that is required when using the Player in a Windows .NET Framework-based application. You can install the Player SDK from the MSDN Web site.

Generally, you should install the Player SDK last because the Player SDK setup can place files in the proper locations better if the Player and Visual Studio folders exist on your hard disk first. This advice doesn't affect your ability to follow along with this article, but it may save you some trouble if you want to use other features of the SDK in the future.

Register the PIA

To use the Player control in your Visual Basic .NET project, you must first register the PIA. Before you do this, though, understanding what the PIA is and why you need to use it might be helpful.

The Player control is a Component Object Model (COM) component. COM technology predates the Framework, so a software layer that allows managed code in the form of Framework assemblies is needed to communicate with unmanaged code in a COM object. (This communication is called COM interoperability.) Interop assemblies are Framework assemblies that enable this translation.

If you have previously used COM components in your Visual Basic .NET projects, you probably haven't noticed much difference from the way they worked in previous versions of Visual Basic. What you may not have realized is that when you reference COM objects, Visual Basic .NET automatically uses interop assemblies behind the scenes. First, Visual Studio .NET inspects the computer repository for shared assemblies, called the global assembly cache (GAC), to determine whether a PIA exists. If a PIA is not found, Visual Studio creates a PIA by using the type library included with the COM component.

There can be disadvantages to using the interop assembly that Visual Studio (or the TlbImp.exe command prompt utility) creates automatically, including performance and versioning problems. The concept of a PIA was invented to resolve these issues. A PIA is created by the publisher of a particular COM component because they are best suited to create the standard interop assembly for that component. A PIA is strongly named and has code signing, so you can be confident that the assembly you are using is the correct one. You should use PIAs in your Framework-based applications that reference COM objects whenever possible.

When you install the Windows Media Player 9 Series SDK, the Player PIA is installed in the folder named Redist in the location where you installed the SDK. The name of the PIA file is Wmppia.dll. The namespace of the assembly is Microsoft.MediaPlayer.Interop; you'll need to reference this namespace in your projects that use the Player control. You'll also need to redistribute the PIA with your applications, so be sure to read the topic "Re-distributing a Primary Interop Assembly" in the Windows Media Player 9 Series SDK.

Registering the PIA really requires two steps: registering the assembly, and adding it to the GAC. Registering the PIA adds an entry in the registry so that Visual Studio .NET can locate and use the PIA. Installing the PIA to the GAC makes the assembly available globally. Microsoft provides command prompt utilities to do each of these actions; if you're interested in what the utilities are and where to find them, you can read the topic "Registering Primary Interop Assemblies for Application Development" in the Player SDK. To make things easier, the Player SDK setup installs a utility that registers the Windows Media Player PIA and adds it to the GAC for you. The name of the utility file is Regpiagac.vbs; you can find it in the folder that contains the TuneClipper C# sample project: \WMPSDK9\Samples\DotNet\Csharp. To locate the correct folder easily, click Start, point to All Programs, point to Windows Media, point to Windows Media SDK, and then click Player SDK Samples. A Web page opens that includes links to all the SDK samples. To open the folder, click the link for TuneClipper near the bottom of the Web page.

To use the Regpiagac utility, simply double-click the file. The file prompts you to provide the paths to the command prompt utilities installed with the Windows .NET Framework SDK and the path to the Player PIA.

If you are using Visual Studio .NET 2002 and you installed Visual Studio .NET and the Player SDK to the default locations, you may be able to use the paths provided by the Regpiagac utility and just click OK, although you may need to change the drive letter in the paths.

If you are using Visual Studio .NET 2003 or you are using a version of .NET Framework newer than version 1.1, you will need to change some of the paths entirely. If this is the case, it is probably easiest first to search your hard drive for Regasm.exe, Gacutil.exe, and wmppia.dll to determine the proper paths.

If you installed any of the software to nonstandard locations, you may experience problems using this utility, especially if the paths contain extra spaces. If this happens, refer to the Windows Media Player 9 Series SDK topic "Registering Primary Interop Assemblies for Application Development" for instructions about how to register the PIA and add it to the GAC manually.

Starting the Project

Now that you've installed the necessary software and registered the Player PIA, you can start Visual Basic and begin creating the project for the sample application. This topic provides you with the procedures for doing so.

Create a project

Follow these steps to create an empty project:

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

  2. From the Visual Basic Projects folder, click Windows Application, type a name for your new project (VBPlayer should do nicely), and then click OK.

    Visual Basic creates a new project for you with a default Windows form named Form1.

  3. In the Properties window, change the form text to "VB Player".

Add the Player control to the project

Next, follow these steps to add a reference to the Windows Media Player control in the project:

  1. Open the Visual Studio Toolbox, and then click Components to display that panel.

  2. Right-click the panel, and then click Add/Remove Items (Customize Toolbox in Visual Studio .NET 2002) to display the dialog box.

  3. On the COM Components tab, select the Windows Media Player check box. (If for some reason Windows Media Player isn't listed, click Browse and locate the file named Wmp.dll.)

  4. Click OK to close the dialog box.

    Visual Studio adds the Windows Media Player control to the toolbox.

Create an instance of the Player control

Now that you've added the Player control to the project, using the control is easy. Simply follow these steps:

  1. Click the Windows Media Player icon in the toolbox to select it, and then click anywhere on the Windows form.

    Visual Studio creates an instance of the control on the form and names it AxWindowsMediaPlayer1.

  2. In the Properties window, change the name to "Player," which will be an easier name to type in code, and change the TabStop property to "False."

  3. Move the control to the upper-left corner of the form and resize it so that it almost fills the width of the form and fills about half of the form vertically. This size should create a usable video and visualization display, and you can see all the default transport controls as well.

    You won't need the transport controls because you'll be creating your own control buttons, so change the Player uiMode property from "full" to "none." To do this, follow these steps:

    1. Right-click the control, and then click Properties to display the dialog box.
    2. In the Select a mode list, click none.
    3. Click OK to close the dialog box.

    The control user interface changes to display only the video and visualization region.

View the generated code

You've done quite a lot so far, but you haven't written a single line of code yet. Of course, Visual Basic has been busy writing code for you, so now is a good time to take a look at that. With your form selected in Solution Explorer, on the View menu, click Code or click the View Code button (if you're new to Visual Studio, it's the one at the upper-left corner of Solution Explorer; it looks like a tiny code window).

To see the generated code, expand the Windows Form Designer generated code region. You should see some code for creating and destroying the form, as well as the code that Visual Studio generated for Windows Media Player. This code is regenerated each time you make a change to your form. This is a wonderful and convenient feature, but if you are using Visual Basic .NET 2002, you may need to comment out the following line of generated code from time to time:

Me.Player.enabled = True

This is not an issue when using Visual Basic .NET 2003.

Add a reference to the PIA

To use the PIA in your code, you need to add a line of code to reference the PIA namespace. At the top of the code window of your form, before any declarations, add the following code:

Imports Microsoft.MediaPlayer.Interop

Imports statements must appear after any Options statements (which you won't have in this project) and before any other code. After you add the statement, the Player control must interoperate by using the PIA instead of any automatically generated interop assembly.

Developing the Application

Now that you have an instance of the Player control connected to the Framework through the PIA, you can add the other elements you need to your form and write the code that makes things happen.

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

  2. From the Windows Forms panel in the toolbox, add a label control to your form.

  3. In the Properties window, change the name of the label to lblTitle and change the default text to Title:. This is the control that will display the title of the current song.

    Next, add three button controls to your form.

  4. Add a button control that will enable the user to open Windows Media files. Change the name of the button to btnOpen and change the default button text to Open.

  5. Add a button control that will function as a play/pause transport control button. Change the name of the button to btnPlayPause, change the default Enabled value to False, and change the default button text to Play.

  6. Add a button control that functions as a stop transport control button. Change the name of the button to btnStop, change the default Enabled value to False, and change the default button text to Stop.

  7. Arrange the controls on the form in a way that is pleasing to you and makes sense to the user. The following diagram shows the completed form layout in the Visual Studio Designer.

Sample Player application in the designer view

Figure 2. Sample Player application in designer view

Write the code

The first step is to begin writing the code that opens Windows Media files in the Player. To automatically switch to code view and edit the code for the button control Click event handler (btnOpen_Click), double-click the Open button on your form. Add the following code to the event handler:

Dim openFileDialog1 As New OpenFileDialog()

'Present the user with a file open dialog box.
openFileDialog1.Filter = "Windows Media Audio (*.wma)|*.wma|Windows Media Video (*.wmv)|*.wmv"
openFileDialog1.RestoreDirectory = True

If openFileDialog1.ShowDialog() = DialogResult.OK Then
    'Open the selected file in the Player.
    Player.URL = openFileDialog1.FileName
End If

When the user clicks Open, this code displays a dialog box the user can use to browse the files on the computer and choose a .wma or .wmv file to play. When the user does this (and clicks OK), the code sets the Player URL property to the file that the user picked. Because the Player autoStart property is set to True by default, the Player immediately opens and plays the digital media file the user chose.

Next, add the code for the play/pause button. In the code window, click btnPlayPause from the class name list. Then, in the method name list, click Click. Add the following code to the btnPlayPause_Click event handler that Visual Basic creates for you:

Select Case Player.playState

    Case WMPPlayState.wmppsPlaying
       Player.Ctlcontrols.pause()

    Case WMPPlayState.wmppsPaused
       Player.Ctlcontrols.play()

Case WMPPlayState.wmppsStopped
       Player.Ctlcontrols.play()
End Select

This code is fairly simple. When the user clicks the play/pause button, the code inspects the Player playState property. If the Player is playing a digital media file, the code pauses the file; if the Player is paused or stopped, the code starts the Player playing files again.

If you have used the Windows Media Player SDK before, the "Ctlcontrols" syntax may look strange to you. In fact, this is simply a reference to the Player Controls object. When Visual Studio encounters a naming conflict in the wrapper class it creates for an ActiveX control, it prefixes the control object, property, method, or event name with the letters "Ctl". This identifies the name as being associated with the control and resolves the conflict. If you are using Visual Studio .NET 2002, you can simply replace any instance of "Ctlcontrols" in this code with "controls".

The code for the stop button is equally simple. In the class name list, click btnStop, and then in the method name list, click Click. Add the following line of code to the btnStop_Click event handler that Visual Basic creates for you:

Player.Ctlcontrols.stop()

The code at this point isn't quite complete because it doesn't do three important things. First, it doesn't manage the enabled state of the play/pause and stop buttons. Second, it doesn't change the play/pause button text to let the user know which function the button performs at any given moment. Third, it doesn't update the text in the title label to display the title of the current digital media. All of this functionality can be created by handling the Player PlayStateChange event.

To add the event handler for Player.PlayStateChange to your code, in the class name list, click Player, and then in the method name list, click PlayStateChange. Add the following code to the Player_PlayStateChange event handler that Visual Basic creates for you:

Select Case e.newState

    Case WMPPlayState.wmppsPlaying  'The Player is playing.
        'Enable the buttons.
        btnPlayPause.Enabled = True
        btnStop.Enabled = True

        'Make btnPlayPause a pause button.
        btnPlayPause.Text = "Pause"

        'Show the title.
        lblTitle.Text = "Title: " & Player.currentMedia.getItemInfoByType("Title", "", 0)

    Case WMPPlayState.wmppsPaused  'The Player is paused.
        'Make btnPlayPause a play button.
        btnPlayPause.Text = "Play"

    Case WMPPlayState.wmppsStopped  'The Player is stopped.
        'Disable the stop button.
        btnStop.Enabled = False

        'Make btnPlayPause a play button.
        btnPlayPause.Text = "Play"

End Select

Whenever the play state changes, this code runs. If the Player is playing (which happens initially when the user opens a file because autoStart is set to True), the code enables the play/pause and stop buttons so the user can use them, and then the code changes the play/pause button text to display Pause to let the user know that the button pauses playback. Finally, the code retrieves the title of the current digital media file and updates the title label text to display the title.

If the Player is paused (which happens when the user clicks the play/pause button), the code simply changes the play/pause button text to display Play to let the user know that the button resumes playback.

If the Player is stopped (which happens when the user clicks the stop button), the code disables the stop button (because the Player is already stopped) and restores the play/pause button text to the default value Play.

Building the Solution

Now that you've completed the code for the sample project, you can build and run the solution.

Build the solution

On the Build menu, click Build Solution. Visual Studio will compile and build the project. If you typed everything correctly, the build process will complete without errors. If the build reports errors, review your code and correct the errors.

Use the sample application

To run the project in the debugger, press F5 on the keyboard. If you encounter the unhandled exception mentioned in the "View the generated code" topic, stop the debugging session, remove or comment the appropriate line of generated code, and then press F5 again.

You can click Open to browse for a .wma or .wmv file, depending on which file type you choose in the Open dialog box. When you select a file, and then click OK, the Open dialog box closes, the digital media file plays, and the transport control buttons change state. You can then use the transport control buttons to pause, restart, or stop playback entirely.

Using IntelliSense with the Player Control

You should know about an issue when using IntelliSense with the Player control. If you are new to Visual Basic .NET, IntelliSense is the feature that provides automatic completion features and syntax tips.

If you typed each line of code in the preceding sample application, you may have noticed something different when you typed this particular line:

lblTitle.Text = "Title: " & Player.currentMedia.getItemInfoByType("Title", "", 0)

Specifically, when you typed Player.currentMedia., IntelliSense didn't list getItemInfoByType as an option. This happens because some of the newer features of the Player control are exposed through interfaces that aren't published in the COM type library, and therefore, are not available to IntelliSense. Nevertheless, you can use these features in Visual Basic just fine; you'll just have to type the full syntax as it appears in the Player SDK documentation.

For More Information

To learn more about Windows Media Player 9 Series, see Windows Media Player 9 Series Help. Windows Media Player 9 Series can be downloaded from the Windows Media page at the Microsoft Web site.

To learn more about the Windows Media Player 9 Series ActiveX control, see the Windows Media Player 9 Series SDK. The Windows Media Player 9 Series SDK can be downloaded from the Windows Media Downloads page at the MSDN Web site.

You can view the most recent Windows Media Player 9 Series SDK documentation online at the MSDN Web site.

To learn more about Visual Basic .NET, see the Visual Basic home page at the MSDN Web site.

To learn more about COM interoperability, see "An Introduction to COM Interop" at the MSDN Web site.

This software is based in part on the work of the Independent JPEG Group.

GIF decompression code, copyright 1990, David Koblas. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. This software is provided "as is" without express or implied warranty.