Play async wav file several times with .net

I have an application in which I need to play a wav file, when a key is pressed, I use the SoundPlayer class, but if another sound is played when a new key is pressed, it stops the sound, playing it again, it looks ugly ....

Is there a way to play the same sound again, even if there is another one?

thanks!

+4
source share
4 answers

Use the PlaySound from the windows API in combination with the SND_ASYNC and SND_NOSTOP .

http://www.pinvoke.net/default.aspx/winmm.playsound

Using

 //And the actual usage PlaySound (fileName, UIntPtr.Zero, (uint)(SoundFlags.SND_FILENAME | SoundFlags.SND_ASYNC | SoundFlags.SND_NOSTOP)); 

ads

 [Flags] public enum SoundFlags { /// <summary>play synchronously (default)</summary> SND_SYNC = 0x0000, /// <summary>play asynchronously</summary> SND_ASYNC = 0x0001, /// <summary>silence (!default) if sound not found</summary> SND_NODEFAULT = 0x0002, /// <summary>pszSound points to a memory file</summary> SND_MEMORY = 0x0004, /// <summary>loop the sound until next sndPlaySound</summary> SND_LOOP = 0x0008, /// <summary>don't stop any currently playing sound</summary> SND_NOSTOP = 0x0010, /// <summary>Stop Playing Wave</summary> SND_PURGE = 0x40, /// <summary>don't wait if the driver is busy</summary> SND_NOWAIT = 0x00002000, /// <summary>name is a registry alias</summary> SND_ALIAS = 0x00010000, /// <summary>alias is a predefined id</summary> SND_ALIAS_ID = 0x00110000, /// <summary>name is file name</summary> SND_FILENAME = 0x00020000, /// <summary>name is resource name or atom</summary> SND_RESOURCE = 0x00040004 } [DllImport("winmm.dll", SetLastError=true)] static extern bool PlaySound(string pszSound, UIntPtr hmod, uint fdwSound); 

Update

Sorry, you're right. The API cannot be used to play sounds simultaneously. You should use waveOut api. Have a look at this article: http://www.codeproject.com/KB/audio-video/cswavrec.aspx

+5
source

NAudio can offer what you need. I did not use it myself, but it is relatively popular.

+1
source

There is a free (for non-commercial applications) sound library for .NET called Irrklang , which supports playing several sounds (at least wav and mp3 from what I can collect), at the same time their tutorial specifically covers this case as the main use of the library.

+1
source

If you ask, “How can I play multiple sounds at once,” then SoundPlayer will never be the answer. PlaySound, I believe, is also limited.

You can see this question and this question for more options on the sound API. I quickly looked at the SDL and SDL Mixer and thought that the SDL was too primitive (you need to mix the sounds yourself), and the SDL Mixer was too heavy (all this and the bag with chips - unlimited mixing and music channels (mp3, ogg, midi, etc.) .d.)). I could not see the online link for BASS C # bindings, but it is free for non-commercial use.

0
source

All Articles