SoundPlayer not playing any bundled windows sounds

2019-07-09 19:20发布

In C# I cannot get SoundPlayer class from System.Media to play any wav from my C:\Windows\Media folder using the following code. All I get is no sound:

String filename = "C:\\Windows\\Media\\tada.wav";
SoundPlayer sp = new SoundPlayer(filename);
sp.Load();
sp.Play();

I have checked the wave file "tada.wav" with a program called "Gspot" that tells me the audio codec is "PCM Audio". I do not receive any compiler warnings or errors and there is no exceptions raised when I run the program. I just do not get any sound. My speakers are on, and I can play the file with Windows Media Player.

Adding the wav as a project resource does not make any difference. Could somebody please help me figure out why I cannot get any sound?

2条回答
Ridiculous、
2楼-- · 2019-07-09 19:32

Are you using this as the body of a main() method in a console application? The application is probably ending, thereby shutting down the thread which plays the audio.

I copied and pasted your code into the main of a new "Visual C# Console Application". I added the "using System.Text;" line at the top of the file, compiled, stepped through it, and it worked. When I ran it (without debugging) I got no sound.

If you add the line:

System.Threading.Thread.Sleep(2000);

After the call to Play(), the application will stay around long enough to play the audio.

查看更多
SAY GOODBYE
3楼-- · 2019-07-09 19:49

The Play() method plays the sound a separate thread. That is, the console app spins a new thread in which to play the sound. This is great for Windows applications so that the sound playing does not stop the Windows main thread. In a console app, when the parent thread ends the child threads all die as well. -- thus no sound.

There is a PlaySync() method that does NOT spawn a new thread and thus will keep the console app thread alive until it has finished playing your sound.

查看更多
登录 后发表回答