How to play audio files(.wav) asynchronously using Windows Forms
Posted by: Suprotim Agarwal ,
on 2/22/2008,
in
Category WinForms & WinRT
Abstract: In this article, we will explore how to play audio files (.wav) asynchronously using Windows Forms. We will be making use of the System.Media.SoundPlayer class which controls playback of a sound from a .wav file.
How to play audio files(.wav) asynchronously using Windows Forms
In this article, we will explore how to play audio files (.wav) asynchronously using Windows Forms. We will be making use of the System.Media.SoundPlayer class which controls playback of a sound from a .wav file. Let us get started.
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
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.
In the coming articles, we will explore how to play video files asynchronously in windows forms. I hope you liked the article and I thank you for viewing it.
If you liked the article, please subscribe to my RSS feed over here.
Was this article worth reading? Share it with fellow developers too. Thanks!