Cet article a fait l'objet d'une traduction manuelle. Déplacez votre pointeur sur les phrases de l'article pour voir la version originale de ce texte. |
Traduction
Source
|
SoundPlayer, classe
Contrôle la lecture du son d'un fichier .wav.
Assembly : System (dans System.dll)
Le type SoundPlayer expose les membres suivants.
| Nom | Description | |
|---|---|---|
|
SoundPlayer() | Initialise une nouvelle instance de la classe SoundPlayer. |
|
SoundPlayer(Stream) | Initialise une nouvelle instance de la classe SoundPlayer et attache le fichier .wav au Stream spécifié. |
|
SoundPlayer(String) | Initialise une nouvelle instance de la classe SoundPlayer et attache le fichier .wav spécifié. |
|
SoundPlayer(SerializationInfo, StreamingContext) | Initialise une nouvelle instance de la classe SoundPlayer. |
| Nom | Description | |
|---|---|---|
|
CanRaiseEvents | Obtient une valeur qui indique si le composant peut déclencher un événement. (Hérité de Component.) |
|
Container | Obtient le IContainer qui contient Component. (Hérité de Component.) |
|
DesignMode | Obtient une valeur qui indique si Component est actuellement en mode design. (Hérité de Component.) |
|
Events | Obtient la liste des gestionnaires d'événements attachés à ce Component. (Hérité de Component.) |
|
IsLoadCompleted | Obtient une valeur indiquant si le chargement d'un fichier .wav s'est terminé correctement. |
|
LoadTimeout | Obtient ou définit le délai de chargement du fichier .wav en millisecondes. |
|
Site | Obtient ou définit le ISite de Component. (Hérité de Component.) |
|
SoundLocation | Obtient ou définit le chemin d'accès ou l'URL du fichier .wav à charger. |
|
Stream | Obtient ou définit le Stream à partir duquel charger le fichier .wav. |
|
Tag | Obtient ou définit Object qui contient les données relatives à SoundPlayer. |
| Nom | Description | |
|---|---|---|
|
CreateObjRef | Crée un objet contenant toutes les informations appropriées requises pour générer un proxy permettant de communiquer avec un objet distant. (Hérité de MarshalByRefObject.) |
|
Dispose() | Libère toutes les ressources utilisées par Component. (Hérité de Component.) |
|
Dispose(Boolean) | Libère les ressources non managées utilisées par Component et libère éventuellement les ressources managées. (Hérité de Component.) |
|
Equals(Object) | Détermine si l'Object spécifié est égal à l'Object en cours. (Hérité de Object.) |
|
Finalize | Libère les ressources non managées et exécute d'autres opérations de nettoyage avant la récupération de Component par le garbage collection. (Hérité de Component.) |
|
GetHashCode | Sert de fonction de hachage pour un type particulier. (Hérité de Object.) |
|
GetLifetimeService | Récupère l'objet de service de durée de vie en cours qui contrôle la stratégie de durée de vie de cette instance. (Hérité de MarshalByRefObject.) |
|
GetService | Retourne un objet qui représente un service fourni par Component ou par son Container. (Hérité de Component.) |
|
GetType | Obtient le Type de l'instance actuelle. (Hérité de Object.) |
|
InitializeLifetimeService | Obtient un objet de service de durée de vie pour contrôler la stratégie de durée de vie de cette instance. (Hérité de MarshalByRefObject.) |
|
Load | Charge un son de façon synchrone. |
|
LoadAsync | Charge un fichier .wav à partir d'un flux de données ou d'une ressource Web à l'aide d'un nouveau thread. |
|
MemberwiseClone() | Crée une copie superficielle de l'objet Object actif. (Hérité de Object.) |
|
MemberwiseClone(Boolean) | Crée une copie superficielle de l'objet MarshalByRefObject actuel. (Hérité de MarshalByRefObject.) |
|
OnLoadCompleted | Déclenche l'événement LoadCompleted. |
|
OnSoundLocationChanged | Déclenche l'événement SoundLocationChanged. |
|
OnStreamChanged | Déclenche l'événement StreamChanged. |
|
Play | Lit le fichier .wav à l'aide d'un nouveau thread, et le charge en premier s'il n'a pas été chargé. |
|
PlayLooping | Lit et met en boucle le fichier .wav à l'aide d'un nouveau thread, et le charge en premier s'il n'a pas été chargé. |
|
PlaySync | Lit le fichier .wav et le charge en premier s'il n'a pas été chargé. |
|
Stop | Arrête la lecture du son, si lecture il y a. |
|
ToString | Retourne String contenant le nom du Component, s'il existe. Cette méthode ne doit pas être substituée. (Hérité de Component.) |
| Nom | Description | |
|---|---|---|
|
Disposed | Se produit lorsque le composant est supprimé par un appel à la méthode Dispose. (Hérité de Component.) |
|
LoadCompleted | Se produit lorsqu'un fichier .wav a été chargé correctement ou non. |
|
SoundLocationChanged | Se produit lorsqu'un nouveau chemin source audio pour ce SoundPlayer a été défini. |
|
StreamChanged | Se produit lorsqu'une nouvelle source audio Stream pour ce SoundPlayer a été définie. |
| Nom | Description | |
|---|---|---|
|
ISerializable.GetObjectData | Pour obtenir une description de ce membre, consultez la méthode ISerializable.GetObjectData. |
La classe SoundPlayer fournit une interface simple pour charger et lire un fichier .wav. La classe SoundPlayer prend en charge le chargement d'un fichier .wav à partir d'un chemin d'accès, d'une URL, d'un Stream qui contient un fichier .wav, ou d'une ressource incorporée qui contient un fichier .wav.
Pour lire un son à l'aide de la classe SoundPlayer, configurez un SoundPlayer avec un chemin d'accès au fichier .wav et appelez l'une des méthodes de lecture. Vous pouvez identifier le fichier .wav à lire en utilisant l'un des constructeurs ou en définissant la propriété SoundLocation ou la propriété Stream. Le fichier peut être chargé avant la lecture en utilisant l'une des méthodes de chargement ou le chargement peut être différé jusqu'à ce que l'une des méthodes de lecture soit appelée. Un SoundPlayer configuré pour charger un fichier .wav à partir d'un Stream ou d'une URL doit le charger dans la mémoire avant que la lecture ne commence.
Vous pouvez charger ou lire un fichier .wav de façon synchrone ou de façon asynchrone. Si vous appelez une méthode de chargement ou de lecture synchrone, le thread appelant attend le retour de la méthode, ce qui peut provoquer l'interruption de la peinture et d'autres événements. L'appel d'une méthode de chargement ou de lecture asynchrone permet au thread appelant de poursuivre sans interruption. Pour plus d'informations sur les appels de méthodes asynchrones, consultez Comment : exécuter une opération en arrière-plan.
Lorsqu'un SoundPlayer a terminé de charger un fichier .wav, il déclenche l'événement LoadCompleted. Vous pouvez examiner le AsyncCompletedEventArgs dans votre gestionnaire d'événements pour déterminer si le chargement a réussi ou a échoué. L'événement SoundLocationChanged est déclenché lorsqu'un nouveau chemin d'accès ou une nouvelle URL est affecté à la source audio. L'événement StreamChanged est déclenché lorsqu'un nouveau Stream est affecté à la source audio. Pour plus d'informations sur la gestion d'événements, consultez Consommation d'événements.
Pour plus d'informations sur SoundPlayer, consultez Vue d'ensemble de la classe SoundPlayer.
Remarque
|
|---|
|
La classe SoundPlayer ne peut pas lire d'autres types de fichier, tels que .wma ou .mp3. Si vous souhaitez lire d'autres types de fichier, vous pouvez utiliser le contrôle Windows Media Player. Pour plus d'informations, consultez Using the Windows Media Player Control in a .NET Framework Solution et Windows Media Player Object Model Reference for Visual Basic .NET and C# dans le Kit de développement (SDK) du Lecteur Windows Media. |
Remarque
|
|---|
|
L'attribut HostProtectionAttribute appliqué à ce type ou membre a la valeur de propriété Resources suivante : UI. HostProtectionAttribute n'affecte pas les applications bureautiques (qui sont généralement démarrées en double-cliquant sur une icône, en tapant une commande ou en entrant une URL dans un navigateur). Pour plus d'informations, consultez la classe HostProtectionAttribute ou Attributs de programmation et de protection des hôtes SQL Server. |
L'exemple de code suivant montre comment utiliser la classe SoundPlayer pour lire des fichiers .wav à partir d'un chemin d'accès local ou d'un URI (Uniform Resource Identifier).
using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Media; using System.Windows.Forms; namespace SoundApiExample { public class SoundTestForm : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox filepathTextbox; private System.Windows.Forms.Button playOnceSyncButton; private System.Windows.Forms.Button playOnceAsyncButton; private System.Windows.Forms.Button playLoopAsyncButton; private System.Windows.Forms.Button selectFileButton; private System.Windows.Forms.Button stopButton; private System.Windows.Forms.StatusBar statusBar; private System.Windows.Forms.Button loadSyncButton; private System.Windows.Forms.Button loadAsyncButton; private SoundPlayer player; public SoundTestForm() { // Initialize Forms Designer generated code. InitializeComponent(); // Disable playback controls until a valid .wav file // is selected. EnablePlaybackControls(false); // Set up the status bar and other controls. InitializeControls(); // Set up the SoundPlayer object. InitializeSound(); } // Sets up the status bar and other controls. private void InitializeControls() { // Set up the status bar. StatusBarPanel panel = new StatusBarPanel(); panel.BorderStyle = StatusBarPanelBorderStyle.Sunken; panel.Text = "Ready."; panel.AutoSize = StatusBarPanelAutoSize.Spring; this.statusBar.ShowPanels = true; this.statusBar.Panels.Add(panel); } // Sets up the SoundPlayer object. private void InitializeSound() { // Create an instance of the SoundPlayer class. player = new SoundPlayer(); // Listen for the LoadCompleted event. player.LoadCompleted += new AsyncCompletedEventHandler(player_LoadCompleted); // Listen for the SoundLocationChanged event. player.SoundLocationChanged += new EventHandler(player_LocationChanged); } private void selectFileButton_Click(object sender, System.EventArgs e) { // Create a new OpenFileDialog. OpenFileDialog dlg = new OpenFileDialog(); // Make sure the dialog checks for existence of the // selected file. dlg.CheckFileExists = true; // Allow selection of .wav files only. dlg.Filter = "WAV files (*.wav)|*.wav"; dlg.DefaultExt = ".wav"; // Activate the file selection dialog. if (dlg.ShowDialog() == DialogResult.OK) { // Get the selected file's path from the dialog. this.filepathTextbox.Text = dlg.FileName; // Assign the selected file's path to // the SoundPlayer object. player.SoundLocation = filepathTextbox.Text; } } // Convenience method for setting message text in // the status bar. private void ReportStatus(string statusMessage) { // If the caller passed in a message... if ((statusMessage != null) && (statusMessage != String.Empty)) { // ...post the caller's message to the status bar. this.statusBar.Panels[0].Text = statusMessage; } } // Enables and disables play controls. private void EnablePlaybackControls(bool enabled) { this.playOnceSyncButton.Enabled = enabled; this.playOnceAsyncButton.Enabled = enabled; this.playLoopAsyncButton.Enabled = enabled; this.stopButton.Enabled = enabled; } private void filepathTextbox_TextChanged(object sender, EventArgs e) { // Disable playback controls until the new .wav is loaded. EnablePlaybackControls(false); } private void loadSyncButton_Click(object sender, System.EventArgs e) { // Disable playback controls until the .wav is // successfully loaded. The LoadCompleted event // handler will enable them. EnablePlaybackControls(false); try { // Assign the selected file's path to // the SoundPlayer object. player.SoundLocation = filepathTextbox.Text; // Load the .wav file. player.Load(); } catch (Exception ex) { ReportStatus(ex.Message); } } private void loadAsyncButton_Click(System.Object sender, System.EventArgs e) { // Disable playback controls until the .wav is // successfully loaded. The LoadCompleted event // handler will enable them. EnablePlaybackControls(false); try { // Assign the selected file's path to // the SoundPlayer object. player.SoundLocation = this.filepathTextbox.Text; // Load the .wav file. player.LoadAsync(); } catch (Exception ex) { ReportStatus(ex.Message); } } // Synchronously plays the selected .wav file once. // If the file is large, UI response will be visibly // affected. private void playOnceSyncButton_Click(object sender, System.EventArgs e) { ReportStatus("Playing .wav file synchronously."); player.PlaySync(); ReportStatus("Finished playing .wav file synchronously."); } // Asynchronously plays the selected .wav file once. private void playOnceAsyncButton_Click(object sender, System.EventArgs e) { ReportStatus("Playing .wav file asynchronously."); player.Play(); } // Asynchronously plays the selected .wav file until the user // clicks the Stop button. private void playLoopAsyncButton_Click(object sender, System.EventArgs e) { ReportStatus("Looping .wav file asynchronously."); player.PlayLooping(); } // Stops the currently playing .wav file, if any. private void stopButton_Click(System.Object sender, System.EventArgs e) { player.Stop(); ReportStatus("Stopped by user."); } // Handler for the LoadCompleted event. private void player_LoadCompleted(object sender, AsyncCompletedEventArgs e) { string message = String.Format("LoadCompleted: {0}", this.filepathTextbox.Text); ReportStatus(message); EnablePlaybackControls(true); } // Handler for the SoundLocationChanged event. private void player_LocationChanged(object sender, EventArgs e) { string message = String.Format("SoundLocationChanged: {0}", player.SoundLocation); ReportStatus(message); } private void playSoundFromResource(object sender, EventArgs e) { System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); System.IO.Stream s = a.GetManifestResourceStream("<AssemblyName>.chimes.wav"); SoundPlayer player = new SoundPlayer(s); player.Play(); } #region Windows Form Designer generated code private void InitializeComponent() { this.filepathTextbox = new System.Windows.Forms.TextBox(); this.selectFileButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.loadSyncButton = new System.Windows.Forms.Button(); this.playOnceSyncButton = new System.Windows.Forms.Button(); this.playOnceAsyncButton = new System.Windows.Forms.Button(); this.stopButton = new System.Windows.Forms.Button(); this.playLoopAsyncButton = new System.Windows.Forms.Button(); this.statusBar = new System.Windows.Forms.StatusBar(); this.loadAsyncButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // filepathTextbox // this.filepathTextbox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.filepathTextbox.Location = new System.Drawing.Point(7, 25); this.filepathTextbox.Name = "filepathTextbox"; this.filepathTextbox.Size = new System.Drawing.Size(263, 20); this.filepathTextbox.TabIndex = 1; this.filepathTextbox.Text = ""; this.filepathTextbox.TextChanged += new System.EventHandler(this.filepathTextbox_TextChanged); // // selectFileButton // this.selectFileButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.selectFileButton.Location = new System.Drawing.Point(276, 25); this.selectFileButton.Name = "selectFileButton"; this.selectFileButton.Size = new System.Drawing.Size(23, 21); this.selectFileButton.TabIndex = 2; this.selectFileButton.Text = "..."; this.selectFileButton.Click += new System.EventHandler(this.selectFileButton_Click); // // label1 // this.label1.Location = new System.Drawing.Point(7, 7); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(145, 17); this.label1.TabIndex = 3; this.label1.Text = ".wav path or URL:"; // // loadSyncButton // this.loadSyncButton.Location = new System.Drawing.Point(7, 53); this.loadSyncButton.Name = "loadSyncButton"; this.loadSyncButton.Size = new System.Drawing.Size(142, 23); this.loadSyncButton.TabIndex = 4; this.loadSyncButton.Text = "Load Synchronously"; this.loadSyncButton.Click += new System.EventHandler(this.loadSyncButton_Click); // // playOnceSyncButton // this.playOnceSyncButton.Location = new System.Drawing.Point(7, 86); this.playOnceSyncButton.Name = "playOnceSyncButton"; this.playOnceSyncButton.Size = new System.Drawing.Size(142, 23); this.playOnceSyncButton.TabIndex = 5; this.playOnceSyncButton.Text = "Play Once Synchronously"; this.playOnceSyncButton.Click += new System.EventHandler(this.playOnceSyncButton_Click); // // playOnceAsyncButton // this.playOnceAsyncButton.Location = new System.Drawing.Point(149, 86); this.playOnceAsyncButton.Name = "playOnceAsyncButton"; this.playOnceAsyncButton.Size = new System.Drawing.Size(147, 23); this.playOnceAsyncButton.TabIndex = 6; this.playOnceAsyncButton.Text = "Play Once Asynchronously"; this.playOnceAsyncButton.Click += new System.EventHandler(this.playOnceAsyncButton_Click); // // stopButton // this.stopButton.Location = new System.Drawing.Point(149, 109); this.stopButton.Name = "stopButton"; this.stopButton.Size = new System.Drawing.Size(147, 23); this.stopButton.TabIndex = 7; this.stopButton.Text = "Stop"; this.stopButton.Click += new System.EventHandler(this.stopButton_Click); // // playLoopAsyncButton // this.playLoopAsyncButton.Location = new System.Drawing.Point(7, 109); this.playLoopAsyncButton.Name = "playLoopAsyncButton"; this.playLoopAsyncButton.Size = new System.Drawing.Size(142, 23); this.playLoopAsyncButton.TabIndex = 8; this.playLoopAsyncButton.Text = "Loop Asynchronously"; this.playLoopAsyncButton.Click += new System.EventHandler(this.playLoopAsyncButton_Click); // // statusBar // this.statusBar.Location = new System.Drawing.Point(0, 146); this.statusBar.Name = "statusBar"; this.statusBar.Size = new System.Drawing.Size(306, 22); this.statusBar.SizingGrip = false; this.statusBar.TabIndex = 9; this.statusBar.Text = "(no status)"; // // loadAsyncButton // this.loadAsyncButton.Location = new System.Drawing.Point(149, 53); this.loadAsyncButton.Name = "loadAsyncButton"; this.loadAsyncButton.Size = new System.Drawing.Size(147, 23); this.loadAsyncButton.TabIndex = 10; this.loadAsyncButton.Text = "Load Asynchronously"; this.loadAsyncButton.Click += new System.EventHandler(this.loadAsyncButton_Click); // // SoundTestForm // this.ClientSize = new System.Drawing.Size(306, 168); this.Controls.Add(this.loadAsyncButton); this.Controls.Add(this.statusBar); this.Controls.Add(this.playLoopAsyncButton); this.Controls.Add(this.stopButton); this.Controls.Add(this.playOnceAsyncButton); this.Controls.Add(this.playOnceSyncButton); this.Controls.Add(this.loadSyncButton); this.Controls.Add(this.label1); this.Controls.Add(this.selectFileButton); this.Controls.Add(this.filepathTextbox); this.MinimumSize = new System.Drawing.Size(310, 165); this.Name = "SoundTestForm"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.Text = "Sound API Test Form"; this.ResumeLayout(false); } #endregion [STAThread] static void Main() { Application.Run(new SoundTestForm()); } } }
Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2
Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.
Remarque