Selecting sounds from Windows and playing them

三世轮回 提交于 2019-12-05 01:36:33

Try this:

    private void Form1_Load(object sender, EventArgs e)
    {

        var systemSounds = new[]
                              {
                                  System.Media.SystemSounds.Asterisk,
                                  System.Media.SystemSounds.Beep,
                                  System.Media.SystemSounds.Exclamation,
                                  System.Media.SystemSounds.Hand,
                                  System.Media.SystemSounds.Question
                              };

        comboBox1.DataSource = systemSounds;

        comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
    }

    void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ((System.Media.SystemSound)comboBox1.SelectedItem).Play();
    }

You do not require any API to play system sounds just write code like this:

// Plays the sound associated with the Asterisk system event.
System.Media.SystemSounds.Asterisk.Play();

The SystemSounds class contains the following predefined system sounds:

  • Asterisk
  • Beep
  • Exclamation
  • Hand
  • Question

All other sounds require you read the desired sound from the registry and play it with code like this:

SoundPlayer simpleSound = new SoundPlayer(@"c:\Path\To\Your\Wave\File.wav");

Sure! All the sounds you're looking for are available through the System.Media.SystemSounds class, where they are exposed as public properties corresponding to the event types that trigger the sounds.

Additionally, objects of the SystemSound class provide a Play method that you can call to play that sound asynchronously.

So for example, to play the "Critical Stop" sound, you would simply write the following code:

System.Media.SystemSounds.Hand.Play();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!