views:

390

answers:

2

How do I play the "New Mail" system sound in C#? This is also called the "Notify" sound.

In Win32, that would be something like

sndPlaySound('Notify', (SND_ALIAS or SND_ASYNC));

So how do you do that in .Net? I know that you can do

System.Media.SystemSounds.Asterisk.Play();

But there's a very limited set of five sounds there - not including whatever the the user has set as the new mail sound.

I can find out which .wav file is being played when I get new mail and play that file, but that won't update when the user's sound scheme is changed.


What I eventually did:

Instead of playing a system sound, I embedded a wav file into the application as a resource, and played it with System.Media.SoundPlayer

+4  A: 

One option is to just PInvoke directly into the sndSound API. Here is the PInvoke definition for that method

public partial class NativeMethods {

    /// Return Type: BOOL->int
    ///pszSound: LPCWSTR->WCHAR*
    ///fuSound: UINT->unsigned int
    [System.Runtime.InteropServices.DllImportAttribute("winmm.dll", EntryPoint="sndPlaySoundW")]
    [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern  bool sndPlaySoundW([System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string pszSound, uint fuSound) ;

    /// SND_APPLICATION -> 0x0080
    public const int SND_APPLICATION = 128;

    /// SND_ALIAS_START -> 0
    public const int SND_ALIAS_START = 0;

    /// SND_RESOURCE -> 0x00040004L
    public const int SND_RESOURCE = 262148;

    /// SND_FILENAME -> 0x00020000L
    public const int SND_FILENAME = 131072;

    /// SND_ALIAS_ID -> 0x00110000L
    public const int SND_ALIAS_ID = 1114112;

    /// SND_NOWAIT -> 0x00002000L
    public const int SND_NOWAIT = 8192;

    /// SND_NOSTOP -> 0x0010
    public const int SND_NOSTOP = 16;

    /// SND_MEMORY -> 0x0004
    public const int SND_MEMORY = 4;

    /// SND_PURGE -> 0x0040
    public const int SND_PURGE = 64;

    /// SND_ASYNC -> 0x0001
    public const int SND_ASYNC = 1;

    /// SND_ALIAS -> 0x00010000L
    public const int SND_ALIAS = 65536;

    /// SND_SYNC -> 0x0000
    public const int SND_SYNC = 0;

    /// SND_LOOP -> 0x0008
    public const int SND_LOOP = 8;

    /// SND_NODEFAULT -> 0x0002
    public const int SND_NODEFAULT = 2;
}
JaredPar
+2  A: 

Actually the new mail sound is the "MailBeep" alias, not the "Notify" alias.

So you want to call PlaySound(L"MailBeep", NULL, SND_SYSTEM | SND_NODEFAULT | SND_ALIAS);

And P/Invoke is definately the way to go here.

Don't forget to specify SND_NODEFAULT or your app will make dings even if the user disables the new mail sound in the control panel.

SND_SYSTEM is new for Windows Vista and causes the sound to be played as a "windows sound" - it's up to you if that's the experience you want to have.

Larry Osterman