Link to home
Avatar of RayT
RayTFlag for United States of America

asked on

How Do I Play An Audio File

How do I play an audio file (mp3, wav, etc.) within a Visual Studio Professional 2019 application?  I want play the audio file asynchronously.  Please provide an example.  Thanks.
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

How do I play an audio file (mp3, wav, etc.) within a Visual Studio Professional 2019 application? 
Here is one of the sample as your reference:

Step 1: Create a new windows application. Open Visual Studio > File > New > Project > Windows Application > Rename it to ‘WindowsPlayAudio’.

Step 2: Drag and drop a label, 2 button controls and an OpenFileDialog component to the form. Rename them as follows :
Label1 – lblFile
Button1 – btnOpen
Button2 – btnPlay
TextBox – txtFileNm
OpenFileDialog – Set the Filter to ‘WAV Files|*.wav’

Step 3: On the ‘btnOpen’ click, display File Open dialog box and accept the selected .wav file in the txtFileNm textbox

Step 4: Code the btnPlay click event to play the selected file asynchronously

Step 5: That’s it. Run the application (F5). Click the Select File button and choose a .wav file. Click on the play button to play the file asynchronously.

Code:
Imports System.Media 

If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            txtFileNm.Text = openFileDialog1.FileName
End If


Private Sub btnPlay_Click(ByVal sender As Object, ByVal e As EventArgs)
      If txtFileNm.Text <> String.Empty Then
            Dim wavPlayer As SoundPlayer = New SoundPlayer()
            wavPlayer.SoundLocation = txtFileNm.Text
AddHandler wavPlayer.LoadCompleted, AddressOf wavPlayer_LoadCompleted
            wavPlayer.LoadAsync()
      End If
End Sub


Private Sub wavPlayer_LoadCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
      CType(sender, System.Media.SoundPlayer).Play()
End Sub

Open in new window


More information:
https://www.dotnetcurry.com/ShowArticle.aspx?ID=115
Avatar of RayT

ASKER

Thanks.  But this only plays wav files.
Noted. Can i know what is the audio format that you're looking forward?
Avatar of RayT

ASKER

Any format.  mp3, wav, m4a

I've done it with Windows Media Player.  I was curious if other ways existed.
ASKER CERTIFIED SOLUTION
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of RayT

ASKER

Thanks!  That's exactly what I need!