Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Play sound in VB.NET

0.00/5 (No votes)
27 Jan 2006 1  
This sample presents a simple solution to play sound (MP3, Wav etc..) in a VB.NET (2003) solution.

Introduction

The Windows Media Player control lets you play MP3 or Wav files with a unique line of VB.NET code:

Me.AxWindowsMediaPlayer1.URL = dlgFileDialog.FileName

Step by step explanation

Step 1

Create a new VBA Windows application in Visual Studio.

Step 2

Add the Media Player control to the toolbox. Right-click the toolbox and choose Add/Remove Items...

Sample screenshot

In the Customize Toolbox window, chose the COM Components panel, and navigate to Windows Media Player and select it.

Sample screenshot

Confirm with the OK button.

Step 3

Add the control to the main form. Select Windows Media Player in the toolbox and add it to the main form.

Sample screenshot

Step 4

Change the Visible property of the control to False.

Sample screenshot

Step 5

Add a Button control to the main form:

Sample screenshot

Step 6

Double-click the Button and add the following code to the Click event procedure:

Private Sub Button1_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _
                          Handles Button1.Click 
    Const DATA_FILE_EXTENSION As String = ".mp3"
    Dim dlgFileDialog As New OpenFileDialog 
    With dlgFileDialog
        .Filter = DATA_FILE_EXTENSION & _
        " files (*" & DATA_FILE_EXTENSION & "|*" & DATA_FILE_EXTENSION 
        .FilterIndex = 1
        .RestoreDirectory = True 
        If .ShowDialog() = DialogResult.OK Then 
            'Play the sound file
         Me.AxWindowsMediaPlayer1.URL = dlgFileDialog.FileName 
        End If 
    End With 
End Sub

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here