문제

For C++ there is a function, PlaySound, that can be used to, uh, play sounds. Is there something like this for C#? I have an application that I want to play a system sound when it starts, to annunciate its initiation.

There has GOT to be a way. I hope.

I want to put this at the end of my Form_Load event:

private void Form1_Load(object sender, EventArgs e)
{
    /* 
       A bunch of configuration and initialization stuff
    */

    PlayBeepBoop();
}

private void PlayBeepBoop()
{
    PlaySystemSound("Beep");
}
도움이 되었습니까?

해결책

There's a SystemSounds class that sounds like what you might want:

SystemSounds.Beep.Play();

It corresponds to whatever "wav" file you have set as the "Default Beep" in Windows' sound settings.

다른 팁

There's three ways I know to play system sounds.

The most generic one is the language agnostic \a character to print, that makes a pretty standard beep sound.

Console.WriteLine("\a");



The second method gives you direct access to a handful of sounds, like 'exclamation' and 'Hand'. They are located in the SystemSounds class (from the Systems.Media namespace) and the usage is pretty straightforward.

SystemSounds.Hand.Play();



Finally, the last method gives you access all the other Windows system sounds. All you have to do is create a SoundPlayer, also located in the Systems.Media namespace, and load a sound manually with it. All system sounds are located at the same place, so it is pretty easy to do.

new System.Media.SoundPlayer(@"C:\Windows\Media\tada.wav").Play();

You can use this class to play any sound in ".wav" format. For example you can find windows sounds in "C:\Windows\Media" (Windows 7) .

public class Wav
{
    [DllImport("winmm.dll", CharSet = CharSet.Auto)]
    private static extern bool PlaySound(String lpszName, IntPtr hModule, Int32 dwFlags);

    public static bool Play(string wavFileName)
    {
        try
        {
            return PlaySound(wavFileName, IntPtr.Zero, 0);
        }
        catch
        {
            return false;
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top