Share via


How to: Play Sounds in an Application

You can add sound to your application by using the System.Media namespace. System sounds, such as a beep, can be played by using System.Media.SystemSounds.Beep.Play(); in an application.

You can also play specific audio files. The following example shows you how to play a waveform audio file that the user has selected.

To play an audio file

  1. On the File menu, click New Project.

  2. In the New Project dialog box, click Windows Forms Application, and then click OK.

    A new Windows Forms project opens.

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

  4. Double-click the button to create 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. Press F5 to run the code.

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

See Also

Tasks

How to: Embed Windows Media Player on a Form

Other Resources

Adding Multimedia to an Application