SoundPlayer Class
Controls playback of a sound from a .wav file.
Assembly: System (in System.dll)
System::MarshalByRefObject
System.ComponentModel::Component
System.Media::SoundPlayer
| Name | Description | |
|---|---|---|
![]() | SoundPlayer() | Initializes a new instance of the SoundPlayer class. |
![]() | SoundPlayer(SerializationInfo^, StreamingContext) | 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. |
| 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 | |
![]() | Events | |
![]() | 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 | |
![]() | 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(Type^) | 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() | |
![]() | Dispose(Boolean) | |
![]() | Equals(Object^) | Determines whether the specified object is equal to the current object.(Inherited from Object.) |
![]() | Finalize() | |
![]() | GetHashCode() | Serves as the default hash function. (Inherited from Object.) |
![]() | GetLifetimeService() | Retrieves the current lifetime service object that controls the lifetime policy for this instance.(Inherited from MarshalByRefObject.) |
![]() | GetService(Type^) | |
![]() | GetType() | |
![]() | 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() | |
![]() | MemberwiseClone(Boolean) | Creates a shallow copy of the current MarshalByRefObject object.(Inherited from MarshalByRefObject.) |
![]() | OnLoadCompleted(AsyncCompletedEventArgs^) | Raises the LoadCompleted event. |
![]() | OnSoundLocationChanged(EventArgs^) | Raises the SoundLocationChanged event. |
![]() | OnStreamChanged(EventArgs^) | 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() |
| Name | Description | |
|---|---|---|
![]() | Disposed | |
![]() | 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(SerializationInfo^, StreamingContext) | 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 NIB: 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. |
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 ); }
Available since 2.0
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.







