Step 7: Add Code to Your Form to Play Sounds

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

You are now ready to add a second SoundPlayer, and then add a method to call each SoundPlayer.

link to videoFor a video version of this topic, see Tutorial 2: Create a Maze in Visual Basic - Video 5 or Tutorial 2: Create a Maze in C# - Video 5.

To play sounds

  1. Start by adding a second SoundPlayer to play the Windows Tada sound. Your game will play this sound when the player reaches the Finish label.

    public partial class Form1 : Form
    {
        // This SoundPlayer plays a sound whenever the player hits a wall.
        System.Media.SoundPlayer startSoundPlayer = new System.Media.SoundPlayer(@"C:\Windows\Media\chord.wav");
    
        // This SoundPlayer plays a sound when the player finishes the game.
        System.Media.SoundPlayer finishSoundPlayer = new System.Media.SoundPlayer(@"C:\Windows\Media\tada.wav");
    
        public Form1()
        {
            InitializeComponent();
            MoveToStart();
        }
    
  2. Both SoundPlayers are now added to your form. Add a Play() method to call the SoundPlayer to play the sound at the appropriate time. You want a sound to play when the user hits a wall. So add the statement startSoundPlayer.Play(); to your MoveToStart() method. Remember to update the comment. The final method looks like the following.

    /// <summary> 
    /// Play a sound, then move the mouse pointer to a point 10 pixels down and to  
    /// the right of the starting point in the upper-left corner of the maze. 
    /// </summary> 
    private void MoveToStart()
    {
        startSoundPlayer.Play();
        Point startingPoint = panel1.Location;
        startingPoint.Offset(10, 10);
        Cursor.Position = PointToScreen(startingPoint);
    }
    
  3. Add the statement finishSoundPlayer.Play(); to the Finish label MouseEnter event handler. Remember to update the comment, because you're changing the code, as follows.

    private void finishLabel_MouseEnter(object sender, EventArgs e)
    {
        // Play a sound, show a congratulatory MessageBox, then close the form.
        finishSoundPlayer.Play();
        MessageBox.Show("Congratulations!");
        Close();
    }
    

To continue or review

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft