共用方式為


步驟 7:將程式碼加入至您的表單以播放音效

您現在可以準備加入第二個 SoundPlayer,然後加入方法來呼叫每一個 SoundPlayer。

若要播放音效

  1. 首先,先加入第二個 SoundPlayer 來播放 Windows 燦爛音效。當玩家到達 [完成] 標籤時,您的遊戲會播放此音效。

    Public Class Form1
    
        ' This SoundPlayer plays a sound whenever the player hits a wall.
        Dim startSoundPlayer = New System.Media.SoundPlayer("C:\Windows\Media\chord.wav")
    
        ' This SoundPlayer plays a sound when the player finishes the game.
        Dim 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
    
    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. 兩個 SoundPlayer 現在都已加入至表單。加入 Play() 方法,在適當時間呼叫 SoundPlayer 來播放音效。例如,您想要在使用者碰觸到圍牆時播放音效。那麼請將陳述式 startSoundPlayer.Play(); 加入至 MoveToStart() 方法。請記得更新註解。最終的方法看起來如下。

    ''' <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
    
    /// <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. 將陳述式 finishSoundPlayer.Play(); 加入至 [完成] 標籤 MouseEnter 事件處理常式。請記得更新註解,因為程式碼也已經變更,如下所示。

    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
    
    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();
    }
    

若要繼續或檢視