153

I have a Windows application written in C#/.NET.

How can I play a specific sound when a button is clicked?

Milan Gardian
  • 11,326
  • 5
  • 38
  • 45
Khilen Maniyar
  • 2,519
  • 7
  • 31
  • 35

7 Answers7

285

You could use:

System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");
player.Play();
bporter
  • 4,467
  • 2
  • 19
  • 29
  • 43
    This is perfect answer because a new user can understand that SoundPlayer belongs to System.Media.... – Khilen Maniyar Aug 22 '10 at 18:11
  • 33
    @Ali... http://stackoverflow.com/questions/2361857/what-does-means-in-c-sharp "It means interpret the following string as literal. Meaning, the \ in the string will actually be a "\" in the output, rather than having to put "\\" to mean the literal character" – Praveen Mar 17 '14 at 15:05
  • @Praveen's answer just gave another informative fact. Thanks to Dexter for asking that "@" symbol. – Allen Linatoc Apr 27 '15 at 07:14
  • 2
    @bporter, this doesn't seem to work with mp3 files; it is restricted to wav format only – Najeeb Nov 19 '16 at 13:49
  • 1
    What a shame this API! It neither plays MP3 nor MIDI files. Completely useless for me. Windows has native support for MP3 and MIDI since at least Windows XP. Shame on Microsoft! – Elmue Sep 04 '18 at 03:50
  • when I only need play standard sound like in messagebox show with icon, I prefer @miroxlav answer for most day to day need for .net windows app. it's simple and quick for example System.Media.SystemSounds.Asterisk.Play(); or System.Media.SystemSounds.Exclamation.Play(); System.Media.SystemSounds.Question.Play(); .etc – gg89 Jan 22 '20 at 08:00
  • You can put the WAV in your exe folder and only pass the WAV name for SoundPlayer. (e.g. `new SoundPlayer("MyWav.wav").Play()`) – Bamdad Jan 06 '22 at 16:09
  • please tell me how to stop playing? – user3398379 Jun 16 '22 at 01:09
107

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ta01
  • 31,040
  • 13
  • 70
  • 99
35

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

Milan Gardian
  • 11,326
  • 5
  • 38
  • 45
ChrisF
  • 134,786
  • 31
  • 255
  • 325
17

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:
miroxlav
  • 11,796
  • 5
  • 58
  • 99
  • 1
    Thank you for this extra information. I'd like to add an example: `System.Media.SystemSounds.Hand.Play(); Thread.Sleep(2000);` plays the sound **Hand**. Note that it plays asynchronously, here I added a sleep command to wait for the completion of the sound. If you don't wait, and play another sound, the previous one stops immediately. – Matt Sep 11 '18 at 13:13
  • @Matt – thank you for sharing. The possible issue with this (although unlikely) is that some user will change their *Hand* sound (as shown in point **2** above) for example to 3 seconds long audio and in that case, their new sound will be stopped after 2 seconds. – miroxlav Nov 06 '20 at 15:05
  • Right, you can't know how long the sound should be playing. Would be great if that could be queried somehow, or if there was a synchronous method waiting until it got played till the end. I [found another question](https://stackoverflow.com/questions/28046275/how-to-get-the-duration-of-mp3-track) dealing with this topic. In one of the answers it is described how you can get a timespan, with that you could determine how many milliseconds the thread.sleep parameter should be. – Matt Nov 06 '20 at 15:43
9

Code bellow allows to play mp3-files and in-memory wave-files too

player.FileName = "123.mp3";
player.Play();

from http://alvas.net/alvas.audio,samples.aspx#sample6 or

Player pl = new Player();
byte[] arr = File.ReadAllBytes(@"in.wav");
pl.Play(arr);

from http://alvas.net/alvas.audio,samples.aspx#sample7

Aleks
  • 492
  • 5
  • 5
3

I think you must firstly add a .wav file to Resources. For example you have sound file named Sound.wav. After you added the Sound.wav file to Resources, you can use this code:

System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.Sound);
player.Play();

This is another way to play sound.

Zoe
  • 27,060
  • 21
  • 118
  • 148
2

To play an Audio file in the Windows form using C# let's check simple example as follows :

1.Go Visual Studio(VS-2008/2010/2012) --> File Menu --> click New Project.

2.In the New Project --> click Windows Forms Application --> Give Name and then click OK.

A new "Windows Forms" project will opens.

3.Drag-and-Drop a Button control from the Toolbox to the Windows Form.

4.Double-click the button to create automatically the default Click event handler, and add the following code.

This code displays the File Open dialog box and passes the results to a method named "playSound" that you will create in the next step.

 OpenFileDialog dialog = new OpenFileDialog();
 dialog.Filter = "Audio Files (.wav)|*.wav";


if(dialog.ShowDialog() == DialogResult.OK)
{
  string path = dialog.FileName;
  playSound(path);
}

5.Add the following method code under the button1_Click event hander.

 private void playSound(string path)
 {
   System.Media.SoundPlayer player = new System.Media.SoundPlayer();
   player.SoundLocation = path;
   player.Load();
   player.Play();
 }

6.Now let's run the application just by Pressing the F5 to run the code.

7.Click the button and select an audio file. After the file loads, the sound will play.

I hope this is useful example to beginners...