Play Audio (.WAV) Files in C#

In this tutorial, I will teach you how to create a program that will only play audio files preferably .wav files using c#. So, now let's start this tutorial! 1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio 2010: Go to File, click New Project, and choose Windows Application. 2. Add two buttons; the browse button for locating audio files and the play button to play the file, and one textbox that displayed the filename of the audio file. design 3. Now, have this code below. Import first the namespace of Media to access SoundPlayer function to play the audio file.
  1. using System.Media;
Now in button1, we will have an openfiledialog that will trigger to open an audio file. And after choosing a audio file, it will display its filename in the textbox.
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. OpenFileDialog openfiledialog1 = new OpenFileDialog();
  4.  
  5. if (openfiledialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  6. {
  7. textBox1.Text = openfiledialog1.FileName;
  8.  
  9. }
  10. }
Lastly, this code is for button2 that will trigger to play the audio file.
  1. private void button2_Click(object sender, EventArgs e)
  2. {
  3.  
  4. try
  5. {
  6. // play the audio file
  7. SoundPlayer audio = new SoundPlayer();
  8. audio.SoundLocation = textBox1.Text;
  9. audio.Load();
  10. audio.Play();
  11. }
  12.  
  13. // if not a .wav file, display the error message
  14. catch (Exception ex)
  15. {
  16. MessageBox.Show(ex.Message);
  17. }
  18.  
  19. }
Output: output For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment