1

I made a kind of Tetris game in C# with a Win Forms Application. I want the program to play-looping a .wav file during the game and another short .wav file only occasionally but parallel to the "main" sound.

I declared at the beginning:

SoundPlayer sp;
SoundPlayer sp2;

Then in the FormLoad Event:

private void Form1_Load(object sender, EventArgs e)
{
  ...
  sp2 = new SoundPlayer(".../tetris.wav");
  sp2.PlayLooping();
  ...
}

Then as far as a line of blocks disappear I want to fire the bomb-sound:

sp = new SoundPlayer(".../bomb.wav");
sp.Play();

The problem is: when the second sound is fired, the first (main) sound stopped. I think this is a thread-problem, but I don't know how to solve this.

Thank you, Filippo

user3283415
  • 119
  • 1
  • 2
  • 12

2 Answers2

0

No this is not a threading problem! SoundPlayer support only one audio play at the same time.

If you need multi sound then you have to use one of the below Tech:

WPF/ MediaPlayer = System.Windows.Media.MediaPlayer(); Open and then Play

DirectX/DirectSound

XNA/SoundEffect

Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70
0

I had been struggling with the same issue.....

The short answer is you can't. The system will only permit one channel to the sound interface within any given process. As such, when you start a new sound, the previous one terminates.

There are a number of work-arounds which mostly use either Direct-X or Media-Player. However, I found neither of those solutions to be either easy or robust in that you are depending on the users machine to have the right things installed.

However, I found a quick and simple solution to the problem.

I added a special "hook" to my application so that when I run it with an appropriate command line argument, all it does is play a particular sound synchronously and quit. I then use the process object to start another instance of the application with the appropriate argument.. and hey presto.. multiple sounds.

If your application is configured to automatically be a single instance, you need to disable that and replace it with a little code to detect another instance and quit.

Another alternative is to add a small exe to your application package that simply does the sound part.

I know it does not sound very "pure", but really, all you are really trying to do with your code is start a temporary background process to play a sound. It doesn't really matter if that process is a windows native function or one of your own making.

Trevor_G
  • 1,331
  • 1
  • 8
  • 17