Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing 2 sounds together at same time

Tags:

c#

.net-3.5

Designing a game for any laptop:

I want to play 2 sounds at the same time! A background music and a sound when pressing on a button!

Using System.Media won't allow me to play 2 sounds together. For background music, I used the following:

SoundPlayer sp = new SoundPlayer(@"..\..\bin\debug\tribal dance.wav");
sp.Play;

If I played another SoundPlayer, the previous one stops!

I want the background music to keep playing until the form is closed! And at the same time, if a button is clicked, another sound will be played with the music!

I also tried added the Windows Media Player to the toolbox and used it (allowing me 2 play 2 sounds at same time). That works fine but the path will give an error if I put it (@""..\..\bin\debug\tribal dance.wav"); and I need to put it that way in order to be read by any computer.

Any suggestions?

like image 443
Chaykha Avatar asked Jan 19 '11 20:01

Chaykha


People also ask

Can you play two audios at once?

If you have ever wanted to play two audio tracks simultaneously on your Android smartphone and wondered how you could do it, you can try out XDA Member KHSH01's Deux - Dual Audio Player app. The app allows you to play two music tracks in sync, such as a vocal track over an instrumental.


1 Answers

You CANNOT play two sounds at once using SoundPlayer.

SoundPlayer is using the native WINAPI PlaySound function to accomplish the task which has no support for playing simultaneous sounds. Creating multiple instances of SoundPlayer won't help.

There are many options most of which involve implementing a lot of the low level API to window's native audio library or DirectSound (note neither are C# and require alot of interop code)

The simplest option would be to depend on windows media player to play the audio for you.

Add a reference to "C:\Windows\System32\wmp.dll"

then use

var player = new WMPLib.WindowsMediaPlayer();
player.URL = @"..\..\bin\debug\tribal dance.wav";

Note: play starts immediately after setting the URL property

The down side of this approach is your reliance on media player for your application to work properly. On the upside, you can use any file format media player supports.

like image 105
MerickOWA Avatar answered Nov 15 '22 03:11

MerickOWA