Поделиться через


Шаг 7. Добавление в форму кода для воспроизведения звуков

Теперь можно добавить второй компонент SoundPlayer, а затем добавить метод, для каждого компонента SoundPlayer.

Воспроизведение звуков

  1. Начните с добавления второго компонента SoundPlayer для воспроизведения звука Tada операционной системы 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();
    }
    

Продолжить или повторить пройденный материал