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’
In the Form1.cs, add the following namespace
C#
using System.Media;
VB.NET
Imports System.Media
Step 3: On the ‘btnOpen’ click, display File Open dialog box and accept the selected .wav file in the txtFileNm textbox
C#
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtFileNm.Text = openFileDialog1.FileName;
}
VB.NET
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
txtFileNm.Text = openFileDialog1.FileName
End If
Step 4: Code the btnPlay click event to play the selected file asynchronously
C#
private void btnPlay_Click(object sender, EventArgs e)
{
if (txtFileNm.Text != String.Empty)
{
SoundPlayer wavPlayer = new SoundPlayer();
wavPlayer.SoundLocation = txtFileNm.Text;
wavPlayer.LoadCompleted += new AsyncCompletedEventHandler(wavPlayer_LoadCompleted);
wavPlayer.LoadAsync();
}
}
private void wavPlayer_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
((System.Media.SoundPlayer)sender).Play();
}
VB.NET
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