Gewusst wie: Asynchrones Laden eines Sounds in einem Windows Form

Im folgenden Codebeispiel wird ein Sound aus einer URL asynchron geladen und anschließend auf einem neuen Thread abgespielt.

Beispiel

Imports System
Imports System.Media
Imports System.Windows.Forms

Public Class Form1
    Inherits System.Windows.Forms.Form

    Friend WithEvents playSoundButton As System.Windows.Forms.Button
    Private WithEvents Player As New SoundPlayer

    Sub New()

        Me.InitializeComponent()

    End Sub

    Private Sub playSoundButton_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles playSoundButton.Click

        ' Replace this file name with a valid file name.
        Me.Player.SoundLocation = "http://www.tailspintoys.com/sounds/stop.wav"
        Me.Player.LoadAsync()

    End Sub

    Private Sub Player_LoadCompleted( _
        ByVal sender As Object, _
        ByVal e As _
        System.ComponentModel.AsyncCompletedEventArgs) _
        Handles Player.LoadCompleted

        If Me.Player.IsLoadCompleted Then
            Me.Player.Play()
        End If

    End Sub

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.playSoundButton = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'playSoundButton
        '
        Me.playSoundButton.Location = New System.Drawing.Point(105, 107)
        Me.playSoundButton.Name = "playSoundButton"
        Me.playSoundButton.Size = New System.Drawing.Size(75, 23)
        Me.playSoundButton.TabIndex = 0
        Me.playSoundButton.Text = "Play Sound"
        Me.playSoundButton.UseVisualStyleBackColor = True
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.playSoundButton)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())
    End Sub

End Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Media;
using System.Windows.Forms;

namespace SoundPlayerLoadAsyncExample
{
    public class Form1 : Form
    {
        private SoundPlayer Player = new SoundPlayer();

        public Form1()
        {
            InitializeComponent();

            this.Player.LoadCompleted += new AsyncCompletedEventHandler(Player_LoadCompleted);
        }

        private void playSoundButton_Click(object sender, EventArgs e)
        {
            this.LoadAsyncSound();
        }

        public void LoadAsyncSound()
        {
            try
            {
                // Replace this file name with a valid file name.
                this.Player.SoundLocation = "http://www.tailspintoys.com/sounds/stop.wav";
                this.Player.LoadAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error loading sound");
            }
        }

        // This is the event handler for the LoadCompleted event.
        void Player_LoadCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (Player.IsLoadCompleted)
            {
                try
                {
                    this.Player.Play();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error playing sound");
                }
            }
        }

        private Button playSoundButton;

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.playSoundButton = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // playSoundButton
            // 
            this.playSoundButton.Location = new System.Drawing.Point(106, 112);
            this.playSoundButton.Name = "playSoundButton";
            this.playSoundButton.Size = new System.Drawing.Size(75, 23);
            this.playSoundButton.TabIndex = 0;
            this.playSoundButton.Text = "Play Sound";
            this.playSoundButton.Click += new System.EventHandler(this.playSoundButton_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.Add(this.playSoundButton);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        #endregion

    }

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }
}

Kompilieren des Codes

Dieses Beispiel setzt Folgendes voraus:

  • Verweise auf die Assemblys System und System.Windows.Forms.

  • Dass der Dateiname "http://www.tailspintoys.com/sounds/stop.wav" durch einen gültigen Dateinamen ersetzt wird.

Informationen zum Erstellen dieses Beispiels über die Befehlszeile für Visual Basic oder Visual C# finden Sie unter Erstellen von der Befehlszeile aus (Visual Basic) oder Erstellen über die Befehlszeile mit csc.exe. Sie können dieses Beispiel auch in Visual Studio erstellen, indem Sie den Code in ein neues Projekt einfügen. Weitere Informationen finden Sie unter Gewusst wie: Kompilieren und Ausführen eines vollständigen Windows Forms-Codebeispiels mit Visual Studio und Gewusst wie: Kompilieren und Ausführen eines vollständigen Windows Forms-Codebeispiels mit Visual Studio und Gewusst wie: Kompilieren und Ausführen eines vollständigen Windows Forms-Codebeispiels mit Visual Studio und Gewusst wie: Kompilieren und Ausführen eines vollständigen Windows Forms-Codebeispiels mit Visual Studio und Gewusst wie: Kompilieren und Ausführen eines vollständigen Windows Forms-Codebeispiels mit Visual Studio.

Robuste Programmierung

Dateioperationen sollten in entsprechende Ausnahmebehandlungsblöcke eingeschlossen sein.

Die folgenden Bedingungen können einen Ausnahmefehler verursachen:

Sicherheit

Beurteilen Sie den Inhalt der Datei nicht anhand des Dateinamens. Bei der Datei Form1.vb handelt es sich zum Beispiel nicht unbedingt um eine Visual Basic-Quelldatei. Überprüfen Sie alle Eingaben, bevor Sie die Daten in der Anwendung verwenden.

Siehe auch

Aufgaben

Gewusst wie: Wiedergabe von Sound in Windows Forms

Referenz

LoadAsync

LoadCompleted

Play

Weitere Ressourcen

SoundPlayer-Klasse