다음을 통해 공유


SoundPlayer 클래스

정의

.wav 파일에서의 소리 재생을 제어합니다.

public ref class SoundPlayer : System::ComponentModel::Component, System::Runtime::Serialization::ISerializable
public class SoundPlayer : System.ComponentModel.Component, System.Runtime.Serialization.ISerializable
[System.Serializable]
public class SoundPlayer : System.ComponentModel.Component, System.Runtime.Serialization.ISerializable
type SoundPlayer = class
    inherit Component
    interface ISerializable
[<System.Serializable>]
type SoundPlayer = class
    inherit Component
    interface ISerializable
Public Class SoundPlayer
Inherits Component
Implements ISerializable
상속
특성
구현

예제

다음 코드 예제에서는 로컬 경로 또는 URI(Uniform Resource Identifier)에서 .wav 파일을 재생하기 위해 클래스를 사용하는 SoundPlayer 방법을 보여 줍니다.

#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 );
}

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 (!string.IsNullOrEmpty(statusMessage))
            {
                // ...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());
        }
    }
}
Imports System.Collections
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Drawing
Imports System.Media
Imports System.Windows.Forms

Public Class SoundTestForm
    Inherits System.Windows.Forms.Form
    Private label1 As System.Windows.Forms.Label
    Private WithEvents filepathTextbox As System.Windows.Forms.TextBox
    Private WithEvents playOnceSyncButton As System.Windows.Forms.Button
    Private WithEvents playOnceAsyncButton As System.Windows.Forms.Button
    Private WithEvents playLoopAsyncButton As System.Windows.Forms.Button
    Private WithEvents selectFileButton As System.Windows.Forms.Button

    Private WithEvents stopButton As System.Windows.Forms.Button
    Private statusBar As System.Windows.Forms.StatusBar
    Private WithEvents loadSyncButton As System.Windows.Forms.Button
    Private WithEvents loadAsyncButton As System.Windows.Forms.Button
    Private player As SoundPlayer


    Public Sub New()

        ' 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()

    End Sub


    ' Sets up the status bar and other controls.
    Private Sub InitializeControls()

        ' Set up the status bar.
        Dim panel As New StatusBarPanel
        panel.BorderStyle = StatusBarPanelBorderStyle.Sunken
        panel.Text = "Ready."
        panel.AutoSize = StatusBarPanelAutoSize.Spring
        Me.statusBar.ShowPanels = True
        Me.statusBar.Panels.Add(panel)

    End Sub


    ' Sets up the SoundPlayer object.
    Private Sub InitializeSound()

        ' Create an instance of the SoundPlayer class.
        player = New SoundPlayer

        ' Listen for the LoadCompleted event.
        AddHandler player.LoadCompleted, AddressOf player_LoadCompleted

        ' Listen for the SoundLocationChanged event.
        AddHandler player.SoundLocationChanged, AddressOf player_LocationChanged

    End Sub


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

        ' Create a new OpenFileDialog.
        Dim dlg As 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() = System.Windows.Forms.DialogResult.OK Then
            ' Get the selected file's path from the dialog.
            Me.filepathTextbox.Text = dlg.FileName

            ' Assign the selected file's path to the SoundPlayer object.
            player.SoundLocation = filepathTextbox.Text
        End If

    End Sub


    ' Convenience method for setting message text in 
    ' the status bar.
    Private Sub ReportStatus(ByVal statusMessage As String)

        ' If the caller passed in a message...
        If (statusMessage IsNot Nothing) AndAlso _
            statusMessage <> [String].Empty Then
            ' ...post the caller's message to the status bar.
            Me.statusBar.Panels(0).Text = statusMessage
        End If

    End Sub


    ' Enables and disables play controls.
    Private Sub EnablePlaybackControls(ByVal enabled As Boolean)

        Me.playOnceSyncButton.Enabled = enabled
        Me.playOnceAsyncButton.Enabled = enabled
        Me.playLoopAsyncButton.Enabled = enabled
        Me.stopButton.Enabled = enabled

    End Sub


    Private Sub filepathTextbox_TextChanged(ByVal sender As Object, _
        ByVal e As EventArgs) Handles filepathTextbox.TextChanged

        ' Disable playback controls until the new .wav is loaded.
        EnablePlaybackControls(False)

    End Sub


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

        ' 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 ex As Exception
            ReportStatus(ex.Message)
        End Try

    End Sub


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

        ' 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 = Me.filepathTextbox.Text

            ' Load the .wav file.
            player.LoadAsync()
        Catch ex As Exception
            ReportStatus(ex.Message)
        End Try

    End Sub


    ' Synchronously plays the selected .wav file once.
    ' If the file is large, UI response will be visibly 
    ' affected.
    Private Sub playOnceSyncButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles playOnceSyncButton.Click

        ReportStatus("Playing .wav file synchronously.")
        player.PlaySync()
        ReportStatus("Finished playing .wav file synchronously.")
    End Sub


    ' Asynchronously plays the selected .wav file once.
    Private Sub playOnceAsyncButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles playOnceAsyncButton.Click

        ReportStatus("Playing .wav file asynchronously.")
        player.Play()

    End Sub


    ' Asynchronously plays the selected .wav file until the user
    ' clicks the Stop button.
    Private Sub playLoopAsyncButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles playLoopAsyncButton.Click

        ReportStatus("Looping .wav file asynchronously.")
        player.PlayLooping()

    End Sub


    ' Stops the currently playing .wav file, if any.
    Private Sub stopButton_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles stopButton.Click

        player.Stop()
        ReportStatus("Stopped by user.")

    End Sub


    ' Handler for the LoadCompleted event.
    Private Sub player_LoadCompleted(ByVal sender As Object, _
        ByVal e As AsyncCompletedEventArgs)

        Dim message As String = [String].Format("LoadCompleted: {0}", _
            Me.filepathTextbox.Text)
        ReportStatus(message)
        EnablePlaybackControls(True)

    End Sub

    ' Handler for the SoundLocationChanged event.
    Private Sub player_LocationChanged(ByVal sender As Object, _
        ByVal e As EventArgs)
        Dim message As String = [String].Format("SoundLocationChanged: {0}", _
            player.SoundLocation)
        ReportStatus(message)
    End Sub

    Private Sub playSoundFromResource(ByVal sender As Object, _
    ByVal e As EventArgs)
        Dim a As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
        Dim s As System.IO.Stream = a.GetManifestResourceStream("<AssemblyName>.chimes.wav")
        Dim player As SoundPlayer = New SoundPlayer(s)
        player.Play()
    End Sub

    Private Sub InitializeComponent()
        Me.filepathTextbox = New System.Windows.Forms.TextBox
        Me.selectFileButton = New System.Windows.Forms.Button
        Me.label1 = New System.Windows.Forms.Label
        Me.loadSyncButton = New System.Windows.Forms.Button
        Me.playOnceSyncButton = New System.Windows.Forms.Button
        Me.playOnceAsyncButton = New System.Windows.Forms.Button
        Me.stopButton = New System.Windows.Forms.Button
        Me.playLoopAsyncButton = New System.Windows.Forms.Button
        Me.statusBar = New System.Windows.Forms.StatusBar
        Me.loadAsyncButton = New System.Windows.Forms.Button
        Me.SuspendLayout()
        ' 
        ' filepathTextbox
        ' 
        Me.filepathTextbox.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles)
        Me.filepathTextbox.Location = New System.Drawing.Point(7, 25)
        Me.filepathTextbox.Name = "filepathTextbox"
        Me.filepathTextbox.Size = New System.Drawing.Size(263, 20)
        Me.filepathTextbox.TabIndex = 1
        Me.filepathTextbox.Text = ""
        ' 
        ' selectFileButton
        ' 
        Me.selectFileButton.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles)
        Me.selectFileButton.Location = New System.Drawing.Point(276, 25)
        Me.selectFileButton.Name = "selectFileButton"
        Me.selectFileButton.Size = New System.Drawing.Size(23, 21)
        Me.selectFileButton.TabIndex = 2
        Me.selectFileButton.Text = "..."
        ' 
        ' label1
        ' 
        Me.label1.Location = New System.Drawing.Point(7, 7)
        Me.label1.Name = "label1"
        Me.label1.Size = New System.Drawing.Size(145, 17)
        Me.label1.TabIndex = 3
        Me.label1.Text = ".wav path or URL:"
        ' 
        ' loadSyncButton
        ' 
        Me.loadSyncButton.Location = New System.Drawing.Point(7, 53)
        Me.loadSyncButton.Name = "loadSyncButton"
        Me.loadSyncButton.Size = New System.Drawing.Size(142, 23)
        Me.loadSyncButton.TabIndex = 4
        Me.loadSyncButton.Text = "Load Synchronously"
        ' 
        ' playOnceSyncButton
        ' 
        Me.playOnceSyncButton.Location = New System.Drawing.Point(7, 86)
        Me.playOnceSyncButton.Name = "playOnceSyncButton"
        Me.playOnceSyncButton.Size = New System.Drawing.Size(142, 23)
        Me.playOnceSyncButton.TabIndex = 5
        Me.playOnceSyncButton.Text = "Play Once Synchronously"
        ' 
        ' playOnceAsyncButton
        ' 
        Me.playOnceAsyncButton.Location = New System.Drawing.Point(149, 86)
        Me.playOnceAsyncButton.Name = "playOnceAsyncButton"
        Me.playOnceAsyncButton.Size = New System.Drawing.Size(147, 23)
        Me.playOnceAsyncButton.TabIndex = 6
        Me.playOnceAsyncButton.Text = "Play Once Asynchronously"
        ' 
        ' stopButton
        ' 
        Me.stopButton.Location = New System.Drawing.Point(149, 109)
        Me.stopButton.Name = "stopButton"
        Me.stopButton.Size = New System.Drawing.Size(147, 23)
        Me.stopButton.TabIndex = 7
        Me.stopButton.Text = "Stop"
        ' 
        ' playLoopAsyncButton
        ' 
        Me.playLoopAsyncButton.Location = New System.Drawing.Point(7, 109)
        Me.playLoopAsyncButton.Name = "playLoopAsyncButton"
        Me.playLoopAsyncButton.Size = New System.Drawing.Size(142, 23)
        Me.playLoopAsyncButton.TabIndex = 8
        Me.playLoopAsyncButton.Text = "Loop Asynchronously"
        ' 
        ' statusBar
        ' 
        Me.statusBar.Location = New System.Drawing.Point(0, 146)
        Me.statusBar.Name = "statusBar"
        Me.statusBar.Size = New System.Drawing.Size(306, 22)
        Me.statusBar.SizingGrip = False
        Me.statusBar.TabIndex = 9
        Me.statusBar.Text = "(no status)"
        ' 
        ' loadAsyncButton
        ' 
        Me.loadAsyncButton.Location = New System.Drawing.Point(149, 53)
        Me.loadAsyncButton.Name = "loadAsyncButton"
        Me.loadAsyncButton.Size = New System.Drawing.Size(147, 23)
        Me.loadAsyncButton.TabIndex = 10
        Me.loadAsyncButton.Text = "Load Asynchronously"
        ' 
        ' SoundTestForm
        '
        Me.ClientSize = New System.Drawing.Size(306, 168)
        Me.Controls.Add(loadAsyncButton)
        Me.Controls.Add(statusBar)
        Me.Controls.Add(playLoopAsyncButton)
        Me.Controls.Add(stopButton)
        Me.Controls.Add(playOnceAsyncButton)
        Me.Controls.Add(playOnceSyncButton)
        Me.Controls.Add(loadSyncButton)
        Me.Controls.Add(label1)
        Me.Controls.Add(selectFileButton)
        Me.Controls.Add(filepathTextbox)
        Me.MinimumSize = New System.Drawing.Size(310, 165)
        Me.Name = "SoundTestForm"
        Me.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show
        Me.Text = "Sound API Test Form"
        Me.ResumeLayout(False)
    End Sub

    <STAThread()> _
    Shared Sub Main()
        Application.Run(New SoundTestForm)
    End Sub
End Class

설명

클래스는 SoundPlayer .wav 파일을 로드하고 재생하기 위한 간단한 인터페이스를 제공합니다. 클래스는 SoundPlayer 파일 경로, URL Stream , .wav 파일이 포함된 또는 .wav 파일이 포함된 포함된 리소스에서 .wav 파일 로드를 지원합니다.

클래스를 사용하여 SoundPlayer 소리를 재생하려면 .wav 파일의 경로를 사용하여 을 구성 SoundPlayer 하고 재생 메서드 중 하나를 호출합니다. 생성자 중 하나를 사용하거나 또는 Stream 속성을 설정하여 재생할 .wav 파일을 식별할 SoundLocation 수 있습니다. 로드 메서드 중 하나를 사용하여 재생하기 전에 파일을 로드하거나 재생 방법 중 하나가 호출될 때까지 로드를 지연할 수 있습니다. SoundPlayer 또는 URL에서 .wav 파일을 로드하도록 구성된 는 Stream 재생이 시작되기 전에 .wav 파일을 메모리에 로드해야 합니다.

.wav 파일을 동기적으로 또는 비동기적으로 로드하거나 재생할 수 있습니다. 동기 로드 또는 재생 메서드를 호출하는 경우 호출 스레드는 메서드가 반환될 때까지 대기하므로 그리기 및 기타 이벤트가 중단될 수 있습니다. 비동기 로드 또는 재생 메서드를 호출하면 중단 없이 호출 스레드를 계속할 수 있습니다. 비동기 메서드 호출에 대한 자세한 내용은 방법: 백그라운드에서 작업 실행을 참조하세요.

SoundPlayer 가 .wav 파일 로드를 마치면 이벤트가 발생합니다LoadCompleted. 이벤트 처리기에서 를 AsyncCompletedEventArgs 검사하여 로드가 성공했는지 또는 실패했는지 확인할 수 있습니다. 오디오 SoundLocationChanged 소스가 새 파일 경로 또는 URL로 설정되면 이벤트가 발생합니다. 오디오 StreamChanged 소스가 새 Stream로 설정되면 이벤트가 발생합니다. 이벤트를 처리 하는 방법에 대 한 자세한 내용은 참조 하세요. 이벤트 처리 및 발생합니다.

에 대한 SoundPlayer자세한 내용은 SoundPlayer 클래스 개요를 참조하세요.

참고

클래스는 SoundPlayer .wma 또는 .mp3 같은 다른 파일 형식을 재생할 수 없습니다. 다른 파일 형식을 재생하려면 Windows 미디어 플레이어 컨트롤을 사용할 수 있습니다. 자세한 내용은 .NET Framework 솔루션에서 Windows 미디어 플레이어 컨트롤 사용 및 Windows 미디어 플레이어 SDK에서 Visual Basic .NET 및 C#에 대한 개체 모델 참조 Windows 미디어 플레이어 참조하세요.

생성자

SoundPlayer()

SoundPlayer 클래스의 새 인스턴스를 초기화합니다.

SoundPlayer(SerializationInfo, StreamingContext)
사용되지 않음.

SoundPlayer 클래스의 새 인스턴스를 초기화합니다.

SoundPlayer(Stream)

SoundPlayer 클래스의 새 인스턴스를 초기화하고 지정된 Stream 내의 .wav 파일을 연결합니다.

SoundPlayer(String)

SoundPlayer 클래스의 새 인스턴스를 초기화하고 지정된 .wav 파일을 연결합니다.

속성

CanRaiseEvents

구성 요소가 이벤트를 발생시킬 수 있는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 Component)
Container

IContainer을 포함하는 Component를 가져옵니다.

(다음에서 상속됨 Component)
DesignMode

Component가 현재 디자인 모드인지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 Component)
Events

Component에 연결된 이벤트 처리기의 목록을 가져옵니다.

(다음에서 상속됨 Component)
IsLoadCompleted

.wav 파일 로드가 성공적으로 완료되었는지 여부를 나타내는 값을 가져옵니다.

LoadTimeout

.wav 파일을 로드해야 할 제한 시간(밀리초)을 가져오거나 설정합니다.

Site

ComponentISite를 가져오거나 설정합니다.

(다음에서 상속됨 Component)
SoundLocation

로드할 .wav 파일의 파일 경로 또는 URL을 가져오거나 설정합니다.

Stream

로드할 .wav 파일이 포함된 Stream을 가져오거나 설정합니다.

Tag

Object에 대한 데이터가 들어 있는 SoundPlayer를 가져오거나 설정합니다.

메서드

CreateObjRef(Type)

원격 개체와 통신하는 데 사용되는 프록시 생성에 필요한 모든 관련 정보가 들어 있는 개체를 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
Dispose()

Component에서 사용하는 모든 리소스를 해제합니다.

(다음에서 상속됨 Component)
Dispose(Boolean)

Component에서 사용하는 관리되지 않는 리소스를 해제하고, 관리되는 리소스를 선택적으로 해제할 수 있습니다.

(다음에서 상속됨 Component)
Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetLifetimeService()
사용되지 않음.

이 인스턴스의 수명 정책을 제어하는 현재의 수명 서비스 개체를 검색합니다.

(다음에서 상속됨 MarshalByRefObject)
GetService(Type)

Component 또는 해당 Container에서 제공하는 서비스를 나타내는 개체를 반환합니다.

(다음에서 상속됨 Component)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
InitializeLifetimeService()
사용되지 않음.

이 인스턴스의 수명 정책을 제어하는 수명 서비스 개체를 가져옵니다.

(다음에서 상속됨 MarshalByRefObject)
Load()

소리를 동기적으로 로드합니다.

LoadAsync()

새 스레드를 사용하여 스트림 또는 웹 리소스에서 .wav 파일을 로드합니다.

MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
MemberwiseClone(Boolean)

현재 MarshalByRefObject 개체의 단순 복사본을 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
OnLoadCompleted(AsyncCompletedEventArgs)

LoadCompleted 이벤트를 발생시킵니다.

OnSoundLocationChanged(EventArgs)

SoundLocationChanged 이벤트를 발생시킵니다.

OnStreamChanged(EventArgs)

StreamChanged 이벤트를 발생시킵니다.

Play()

새 스레드를 사용하여 .wav 파일을 재생하며, .wav 파일이 아직 로드되지 않았으면 먼저 .wav 파일을 로드합니다.

PlayLooping()

새 스레드를 사용하여 .wav 파일을 재생 및 반복하며, .wav 파일이 아직 로드되지 않았으면 먼저 .wav 파일을 로드합니다.

PlaySync()

.wav 파일을 재생하며, .wav 파일이 아직 로드되지 않았으면 먼저 .wav 파일을 로드합니다.

Stop()

소리가 재생 중인 경우 재생을 중지합니다.

ToString()

Component의 이름이 포함된 String을 반환합니다(있는 경우). 이 메서드는 재정의할 수 없습니다.

(다음에서 상속됨 Component)

이벤트

Disposed

Dispose() 메서드를 호출하여 구성 요소를 삭제할 때 발생합니다.

(다음에서 상속됨 Component)
LoadCompleted

성공 여부에 관계없이 .wav 파일의 로드가 완료될 때 발생합니다.

SoundLocationChanged

SoundPlayer의 새 오디오 소스 경로가 설정되었을 때 발생합니다.

StreamChanged

Stream의 새 SoundPlayer 오디오 소스가 설정되었을 때 발생합니다.

명시적 인터페이스 구현

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

이 멤버에 대한 설명을 보려면 GetObjectData(SerializationInfo, StreamingContext) 메서드를 참조하세요.

적용 대상

추가 정보