Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a sound in C#, .NET

Tags:

c#

.net

audio

People also ask

How to use sound in c program?

The Beep function in C is used to make a Beep sound. It generates a tone on the speaker. The function is synchronous, i.e. it waits and doesn't return to its caller function until the sound is finished. It can be very useful during the Debugging process for finding errors.

How to do beep sound in C?

The "\a" escape sequence is used to make a beep sound i.e., it is used to generate a tone sound on the speaker.

How do I run a C program file?

Opening a file is performed using the fopen() function defined in the stdio.h header file. The syntax for opening a file in standard I/O is: ptr = fopen("fileopen","mode");

What is \A in C?

It is an ascii character and can be used anywhere. \a Is used to display a sound.


You could use:

System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");
player.Play();

You can use SystemSound, for example, System.Media.SystemSounds.Asterisk.Play();.


For Windows Forms one way is to use the SoundPlayer

private void Button_Click(object sender, EventArgs e)
{
    using (var soundPlayer = new SoundPlayer(@"c:\Windows\Media\chimes.wav")) {
        soundPlayer.Play(); // can also use soundPlayer.PlaySync()
    }
}

MSDN page

This will also work with WPF, but you have other options like using MediaPlayer MSDN page


Additional Information.

This is a bit high-level answer for applications which want to seamlessly fit into the Windows environment. Technical details of playing particular sound were provided in other answers. Besides that, always note these two points:

  1. Use five standard system sounds in typical scenarios, i.e.

    • Asterisk - play when you want to highlight current event

    • Question - play with questions (system message box window plays this one)

    • Exclamation - play with excalamation icon (system message box window plays this one)

    • Beep (default system sound)

    • Critical stop ("Hand") - play with error (system message box window plays this one)
       

    Methods of class System.Media.SystemSounds will play them for you.
     

  2. Implement any other sounds as customizable by your users in Sound control panel

    • This way users can easily change or remove sounds from your application and you do not need to write any user interface for this – it is already there
    • Each user profile can override these sounds in own way
    • How-to:
      • Create sound profile of your application in the Windows Registry (Hint: no need of programming, just add the keys into installer of your application.)
      • In your application, read sound file path or DLL resource from your registry keys and play it. (How to play sounds you can see in other answers.)