Step 7: Add Code to Your Form to Play Sounds
You are now ready to add a second SoundPlayer, and then add a method to call each SoundPlayer.
For 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
-
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(); }
-
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); }
-
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.
To continue or review
-
To go to the next tutorial step, see Step 8: Run Your Program and Try Other Features.
-
To return to the previous tutorial step, see Step 6: Add a SoundPlayer.