SoundPlayer Class
Controls playback of a sound from a .wav file.
System::MarshalByRefObject
System.ComponentModel::Component
System.Media::SoundPlayer
Assembly: System (in System.dll)
The SoundPlayer type exposes the following members.
| Name | Description | |
|---|---|---|
![]() | SoundPlayer() | Initializes a new instance of the SoundPlayer class. |
![]() | SoundPlayer(Stream) | Initializes a new instance of the SoundPlayer class, and attaches the .wav file within the specified Stream. |
![]() | SoundPlayer(String) | Initializes a new instance of the SoundPlayer class, and attaches the specified .wav file. |
![]() | SoundPlayer(SerializationInfo, StreamingContext) | Initializes a new instance of the SoundPlayer class. |
| Name | Description | |
|---|---|---|
![]() | CanRaiseEvents | Gets a value indicating whether the component can raise an event. (Inherited from Component.) |
![]() | Container | Gets the IContainer that contains the Component. (Inherited from Component.) |
![]() | DesignMode | Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.) |
![]() | Events | Gets the list of event handlers that are attached to this Component. (Inherited from Component.) |
![]() | IsLoadCompleted | Gets a value indicating whether loading of a .wav file has successfully completed. |
![]() | LoadTimeout | Gets or sets the time, in milliseconds, in which the .wav file must load. |
![]() | Site | Gets or sets the ISite of the Component. (Inherited from Component.) |
![]() | SoundLocation | Gets or sets the file path or URL of the .wav file to load. |
![]() | Stream | Gets or sets the Stream from which to load the .wav file. |
![]() | Tag | Gets or sets the Object that contains data about the SoundPlayer. |
| Name | Description | |
|---|---|---|
![]() | CreateObjRef | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) |
![]() | Dispose() | Releases all resources used by the Component. (Inherited from Component.) |
![]() | Dispose(Boolean) | Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.) |
![]() | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) |
![]() | Finalize | Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.) |
![]() | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) |
![]() | GetLifetimeService | Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) |
![]() | GetService | Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.) |
![]() | GetType | Gets the Type of the current instance. (Inherited from Object.) |
![]() | InitializeLifetimeService | Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) |
![]() | Load | Loads a sound synchronously. |
![]() | LoadAsync | Loads a .wav file from a stream or a Web resource using a new thread. |
![]() | MemberwiseClone() | Creates a shallow copy of the current Object. (Inherited from Object.) |
![]() | MemberwiseClone(Boolean) | Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) |
![]() | OnLoadCompleted | Raises the LoadCompleted event. |
![]() | OnSoundLocationChanged | Raises the SoundLocationChanged event. |
![]() | OnStreamChanged | Raises the StreamChanged event. |
![]() | Play | Plays the .wav file using a new thread, and loads the .wav file first if it has not been loaded. |
![]() | PlayLooping | Plays and loops the .wav file using a new thread, and loads the .wav file first if it has not been loaded. |
![]() | PlaySync | Plays the .wav file and loads the .wav file first if it has not been loaded. |
![]() | Stop | Stops playback of the sound if playback is occurring. |
![]() | ToString | Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.) |
| Name | Description | |
|---|---|---|
![]() | Disposed | Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.) |
![]() | LoadCompleted | Occurs when a .wav file has been successfully or unsuccessfully loaded. |
![]() | SoundLocationChanged | Occurs when a new audio source path for this SoundPlayer has been set. |
![]() | StreamChanged | Occurs when a new Stream audio source for this SoundPlayer has been set. |
| Name | Description | |
|---|---|---|
![]() ![]() | ISerializable::GetObjectData | For a description of this member, see the ISerializable::GetObjectData method. |
The SoundPlayer class provides a simple interface for loading and playing a .wav file. The SoundPlayer class supports loading a .wav file from a file path, a URL, a Stream that contains a .wav file, or an embedded resource that contains a .wav file.
To play a sound using the SoundPlayer class, configure a SoundPlayer with a path to the .wav file and call one of the play methods. You can identify the .wav file to play by using one of the constructors or by setting either the SoundLocation or Stream property. The file can be loaded prior to playing by using one of the load methods, or loading can be deferred until one of the play methods is called. A SoundPlayer configured to load a .wav file from a Stream or URL must load the .wav file into memory before playback begins.
You can load or play a .wav file synchronously or asynchronously. If you call a synchronous load or play method, the calling thread will wait until the method returns, which may cause painting and other events to be interrupted. Calling an asynchronous load or play method will allow the calling thread to continue without interruption. For more information on asynchronous method calls, see How to: Run an Operation in the Background.
When a SoundPlayer has finished loading a .wav file, it raises the LoadCompleted event. You can examine the AsyncCompletedEventArgs in your event handler to determine if the load succeeded or failed. The SoundLocationChanged event is raised when the audio source is set to a new file path or URL. The StreamChanged event is raised when the audio source is set to a new Stream. For more information about handling events, see Consuming Events.
For more information about SoundPlayer, see SoundPlayer Class Overview.
Note |
|---|
The SoundPlayer class cannot play other file types, such as .wma or .mp3. If you want to play other file types, you can use the Windows Media Player control. For more information, see Using the Windows Media Player Control in a .NET Framework Solution and Windows Media Player Object Model Reference for Visual Basic .NET and C# in the Windows Media Player SDK. |
Note |
|---|
The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: UI. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes. |
The following code example demonstrates the use of the SoundPlayer class for playing .wav files from a local path or a Uniform Resource Identifier (URI).
#using <System.Drawing.dll> #using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Collections; using namespace System::ComponentModel; using namespace System::Diagnostics; using namespace System::Drawing; using namespace System::Media; using namespace System::Windows::Forms; public ref class SoundTestForm: public System::Windows::Forms::Form { private: System::Windows::Forms::Label ^ label1; System::Windows::Forms::TextBox^ filepathTextbox; System::Windows::Forms::Button^ playOnceSyncButton; System::Windows::Forms::Button^ playOnceAsyncButton; System::Windows::Forms::Button^ playLoopAsyncButton; System::Windows::Forms::Button^ selectFileButton; System::Windows::Forms::Button^ stopButton; System::Windows::Forms::StatusBar^ statusBar; System::Windows::Forms::Button^ loadSyncButton; System::Windows::Forms::Button^ loadAsyncButton; 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(); } private: // Sets up the status bar and other controls. void InitializeControls() { // Set up the status bar. StatusBarPanel^ panel = gcnew 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. void InitializeSound() { // Create an instance of the SoundPlayer class. player = gcnew SoundPlayer; // Listen for the LoadCompleted event. player->LoadCompleted += gcnew AsyncCompletedEventHandler( this, &SoundTestForm::player_LoadCompleted ); // Listen for the SoundLocationChanged event. player->SoundLocationChanged += gcnew EventHandler( this, &SoundTestForm::player_LocationChanged ); } void selectFileButton_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { // Create a new OpenFileDialog. OpenFileDialog^ dlg = gcnew 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. void ReportStatus( String^ statusMessage ) { // If the caller passed in a message... if ( (statusMessage != nullptr) && (statusMessage != String::Empty) ) { // ...post the caller's message to the status bar. this->statusBar->Panels[ 0 ]->Text = statusMessage; } } // Enables and disables play controls. void EnablePlaybackControls( bool enabled ) { this->playOnceSyncButton->Enabled = enabled; this->playOnceAsyncButton->Enabled = enabled; this->playLoopAsyncButton->Enabled = enabled; this->stopButton->Enabled = enabled; } void filepathTextbox_TextChanged( Object^ /*sender*/, EventArgs^ /*e*/ ) { // Disable playback controls until the new .wav is loaded. EnablePlaybackControls( false ); } 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 ); } } 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. 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. 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. void playLoopAsyncButton_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { ReportStatus( "Looping .wav file asynchronously." ); player->PlayLooping(); } // Stops the currently playing .wav file, if any. void stopButton_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) { player->Stop(); ReportStatus( "Stopped by user." ); } // Handler for the LoadCompleted event. 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. void player_LocationChanged( Object^ /*sender*/, EventArgs^ /*e*/ ) { String^ message = String::Format( "SoundLocationChanged: {0}", player->SoundLocation ); ReportStatus( message ); } void InitializeComponent() { this->filepathTextbox = gcnew System::Windows::Forms::TextBox; this->selectFileButton = gcnew System::Windows::Forms::Button; this->label1 = gcnew System::Windows::Forms::Label; this->loadSyncButton = gcnew System::Windows::Forms::Button; this->playOnceSyncButton = gcnew System::Windows::Forms::Button; this->playOnceAsyncButton = gcnew System::Windows::Forms::Button; this->stopButton = gcnew System::Windows::Forms::Button; this->playLoopAsyncButton = gcnew System::Windows::Forms::Button; this->statusBar = gcnew System::Windows::Forms::StatusBar; this->loadAsyncButton = gcnew 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 = System::Drawing::Point( 7, 25 ); this->filepathTextbox->Name = "filepathTextbox"; this->filepathTextbox->Size = System::Drawing::Size( 263, 20 ); this->filepathTextbox->TabIndex = 1; this->filepathTextbox->Text = ""; this->filepathTextbox->TextChanged += gcnew System::EventHandler( this, &SoundTestForm::filepathTextbox_TextChanged ); // // selectFileButton // this->selectFileButton->Anchor = static_cast<AnchorStyles>(AnchorStyles::Top | AnchorStyles::Right); this->selectFileButton->Location = System::Drawing::Point( 276, 25 ); this->selectFileButton->Name = "selectFileButton"; this->selectFileButton->Size = System::Drawing::Size( 23, 21 ); this->selectFileButton->TabIndex = 2; this->selectFileButton->Text = "..."; this->selectFileButton->Click += gcnew System::EventHandler( this, &SoundTestForm::selectFileButton_Click ); // // label1 // this->label1->Location = System::Drawing::Point( 7, 7 ); this->label1->Name = "label1"; this->label1->Size = System::Drawing::Size( 145, 17 ); this->label1->TabIndex = 3; this->label1->Text = ".wav path or URL:"; // // loadSyncButton // this->loadSyncButton->Location = System::Drawing::Point( 7, 53 ); this->loadSyncButton->Name = "loadSyncButton"; this->loadSyncButton->Size = System::Drawing::Size( 142, 23 ); this->loadSyncButton->TabIndex = 4; this->loadSyncButton->Text = "Load Synchronously"; this->loadSyncButton->Click += gcnew System::EventHandler( this, &SoundTestForm::loadSyncButton_Click ); // // playOnceSyncButton // this->playOnceSyncButton->Location = System::Drawing::Point( 7, 86 ); this->playOnceSyncButton->Name = "playOnceSyncButton"; this->playOnceSyncButton->Size = System::Drawing::Size( 142, 23 ); this->playOnceSyncButton->TabIndex = 5; this->playOnceSyncButton->Text = "Play Once Synchronously"; this->playOnceSyncButton->Click += gcnew System::EventHandler( this, &SoundTestForm::playOnceSyncButton_Click ); // // playOnceAsyncButton // this->playOnceAsyncButton->Location = System::Drawing::Point( 149, 86 ); this->playOnceAsyncButton->Name = "playOnceAsyncButton"; this->playOnceAsyncButton->Size = System::Drawing::Size( 147, 23 ); this->playOnceAsyncButton->TabIndex = 6; this->playOnceAsyncButton->Text = "Play Once Asynchronously"; this->playOnceAsyncButton->Click += gcnew System::EventHandler( this, &SoundTestForm::playOnceAsyncButton_Click ); // // stopButton // this->stopButton->Location = System::Drawing::Point( 149, 109 ); this->stopButton->Name = "stopButton"; this->stopButton->Size = System::Drawing::Size( 147, 23 ); this->stopButton->TabIndex = 7; this->stopButton->Text = "Stop"; this->stopButton->Click += gcnew System::EventHandler( this, &SoundTestForm::stopButton_Click ); // // playLoopAsyncButton // this->playLoopAsyncButton->Location = System::Drawing::Point( 7, 109 ); this->playLoopAsyncButton->Name = "playLoopAsyncButton"; this->playLoopAsyncButton->Size = System::Drawing::Size( 142, 23 ); this->playLoopAsyncButton->TabIndex = 8; this->playLoopAsyncButton->Text = "Loop Asynchronously"; this->playLoopAsyncButton->Click += gcnew System::EventHandler( this, &SoundTestForm::playLoopAsyncButton_Click ); // // statusBar // this->statusBar->Location = System::Drawing::Point( 0, 146 ); this->statusBar->Name = "statusBar"; this->statusBar->Size = System::Drawing::Size( 306, 22 ); this->statusBar->SizingGrip = false; this->statusBar->TabIndex = 9; this->statusBar->Text = "(no status)"; // // loadAsyncButton // this->loadAsyncButton->Location = System::Drawing::Point( 149, 53 ); this->loadAsyncButton->Name = "loadAsyncButton"; this->loadAsyncButton->Size = System::Drawing::Size( 147, 23 ); this->loadAsyncButton->TabIndex = 10; this->loadAsyncButton->Text = "Load Asynchronously"; this->loadAsyncButton->Click += gcnew System::EventHandler( this, &SoundTestForm::loadAsyncButton_Click ); // // SoundTestForm // this->ClientSize = 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 = System::Drawing::Size( 310, 165 ); this->Name = "SoundTestForm"; this->SizeGripStyle = System::Windows::Forms::SizeGripStyle::Show; this->Text = "Sound API Test Form"; this->ResumeLayout( false ); } }; [STAThread] int main() { Application::Run( gcnew SoundTestForm ); }
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.







Note