how to play a .wav file using c#

2019-08-22 07:07发布

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

2条回答
Juvenile、少年°
2楼-- · 2019-08-22 07:44

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.

查看更多
做自己的国王
3楼-- · 2019-08-22 07:56

I have put your wave file in my local drive (D:) and try with .NET Framework 3.0 until .NET Framework 4.5 all of them play the sound .here is my code or your code ;)

 const string soundLocation = @"D:\\file_example_WAV_1MG.wav";
 System.Media.SoundPlayer player = new System.Media.SoundPlayer(soundLocation);
 player.Play();
查看更多
登录 后发表回答