Search code examples
c#.netmediaplaybackvoice

how to play a .wav file using c#


I am new to System.Media and I want to simply play the sound of a .wav file using c# I did exactly what is written in this question's answars](How to play a sound in C#, .NET) and it won't work. I used special .wav file that is especially for testing so it can`t be the problem. the file path cant be the problem either, as I copied it and not manually typed it.

I don't know what have I done wrong, no errors. thank you in advance!

here is the code

// using System.Media;
  const string soundLocation = @"cannot share the actual path but its not the problem anyway";
            System.Media.SoundPlayer player = new System.Media.SoundPlayer(soundLocation);
            player.Play();

wav file


Solution

  • If you want the sound to play, you could use:

    player.PlaySync();
    

    rather than:

    player.Play();
    

    The reason that the latter doesn't work is that your program exits too quickly (once execution gets to the end of the Main method). PlaySync avoids this issue by using the current thread rather than a new thread.