logo
Учебник_ПОА

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.

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

  2. 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);

    }

  3. 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();

    }

  4. Press F5 to run the code.

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