Play wav file async multiple times with .net

后端 未结 4 1050
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 19:00

I have an app that I need to play a wav file when a key is pressed, I use the SoundPlayer class but if another sound is being played when a new key is pressed, it stops the

4条回答
  •  春和景丽
    2020-12-10 19:36

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

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

    Usage

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

    Declarations

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

    Update

    Apologies, you are correct. The API cannot be used to play sounds simultaneously. You should be using the waveOut api. Look at this article: http://www.codeproject.com/KB/audio-video/cswavrec.aspx

提交回复
热议问题