SoFunction
Updated on 2025-03-08

Four ways to play sounds in c#

The first is to use DirectX

1. Install the DirectX SDK (with 9 DLL files). Here we only use and
2. Introduce the namespace of the DLL file of DirectX:

 using ;
 using ;

3. Build the equipment

Device dv=new Device();

4. Set CooperativeLevel. Because Windows is a multi-tasking system, the device is not exclusive

SecondaryBuffer buf=new SecondaryBuffer(@"",dv);

5. Open up a buffer zone

SecondaryBuffer buf=new SecondaryBuffer(@"",dv);

6. It will be played next. The first parameter indicates priority level, and 0 is the lowest. The second parameter is the playback method, here is loop playback.

 (0,);

The second is to use Microsoft speech object Library

/// <summary

  /// Play sound files
  /// </summary>

  /// <param name="FileName">File full name</param>
  public void PlaySound(string FileName)

  {//To load COM component: Microsoft speech object Library
   if (!(FileName))

   {

    return;

   }

    pp = new ();

 

    spFs = new ();

 

   (FileName, , true);

    Istream = spFs as ;

   (Istream, );

   ();

  }

The third type: Quote SoundPlayer

 sndPlayer = new (+@"/");

();

Type 4: Using Windows Media Player

Create a new C# Windows Form project (Windows application) and define two menu buttons (menuItem1,menuItem2).
Select "Custom Toolbox (Add/Remove Toolbox Items)" in "Tools" in the menu. In the window of the custom toolbox, click to expand the "COM Components" item and select the "Window Media Player" option. After confirmation, the item "Windows Media Player" will appear in the "Toolbox", and then drag it onto the Form to resize. The system will automatically add a reference to this dll in the "Reference". AxMediaPlayer is the Namespace and class we use.
Set some properties of this control in the property bar. For convenience, here I set AutoStart to true (actually true by default). As long as FileName is set (the file is opened), the file will automatically play. The complete code is as follows:

private void menuItem1_Click(object sender,  e)
{
OpenFileDialog ofDialog = new OpenFileDialog();
 = true;
 = true;
 = true;



//the next sentence must be in single line
 = "VCDdocument(*.dat)|*.dat|Audiodocument(*.avi)|*.avi
  |WAVdocument(*.wav)|*.wav|MP3document(*.mp3)|*.mp3|所有document (*.*)|*.*";



 = "*.mp3";
if(() == )
{
// 2003 version method this. = ;this.= ;//2005 Usage
}
}

This is a Microsoft player. You can also try Winamp controls. If you only need to play sounds without displaying them, you just need to set the Visible property of AxMediaPlayer to false.

The above is the detailed content of the four methods of playing sound in c#. For more information about playing sound in c#, please follow my other related articles!