This topic has not yet been rated - Rate this topic

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 Class Form1
    
        ' This SoundPlayer plays a sound whenever the player hits a wall. 
        Private startSoundPlayer = New System.Media.SoundPlayer("C:\Windows\Media\chord.wav")
    
        ' This SoundPlayer plays a sound when the player finishes the game. 
        Private finishSoundPlayer = New System.Media.SoundPlayer("C:\Windows\Media\tada.wav")
    
        Public Sub New()
            ' This call is required by Windows Forms Designer.
            InitializeComponent()
            ' Add any initialization after the InitializeComponent() call.
            MoveToStart()
        End Sub
    
  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> 
    ''' <remarks></remarks> 
    Private Sub MoveToStart()
        startSoundPlayer.Play()
        Dim startingPoint = Panel1.Location
        startingPoint.Offset(10, 10)
        Cursor.Position = PointToScreen(startingPoint)
    End Sub
    
  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 Sub finishLabel_MouseEnter() Handles finishLabel.MouseEnter
        ' Play a sound, show a congratulatory MessageBox, then close the form.
        finishSoundPlayer.Play()
        MessageBox.Show("Congratulations!")
        Close()
    End Sub
    

To continue or review

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.