This article introduces how C# plays sound with examples. The main implementation steps are as follows:
1. First import the following two functions:
/// <summary> /// Send control commands to the media control interface/// </summary> /// <param name="lpszCommand"> command, see/// /en-us/library/windows/desktop/dd743572(v=vs.85).aspx </param> /// The information returned by the <param name="lpszReturnString"> command, if there is no information returned, it can be null</param>/// <param name="cchReturn">Specify the string size of the return information</param>/// <param name="hwndCallback">Callback handle, if the notify flag is not specified in the command parameter, it can be new IntPtr(0)</param>/// <returns>Return the error code to execute the command</returns>[DllImport("")] static extern Int32 mciSendString(string lpszCommand, StringBuilder returnString, int bufferSize, IntPtr hwndCallback); /// <summary> /// Returns the description of the execution status error code/// </summary> /// <param name="errorCode">Error code returned by mciSendCommand or mciSendString</param>/// <param name="errorText">Description string for error code</param>/// <param name="errorTextSize">Specify the size of the string</param>/// <returns> If ERROR Code is unknown, return false</returns>[DllImport("")] static extern bool mciGetErrorString(Int32 errorCode, StringBuilder errorText, Int32 errorTextSize);
2. The sample code is as follows:
int error = mciSendString("open C:\\Users\\Angel\\Desktop\\ alias myDivece", null, 0, new IntPtr(0)); if (error == 0) { mciSendString("play myDivece", null, 0, new IntPtr(0)); //Play} else { StringBuilder errorText = new StringBuilder(); mciGetErrorString(error, errorText, 50); (()); }
3. Playback control can be performed through the following statements:
mciSendString("play myDivece", null, 0, new IntPtr(0)); //PlaymciSendString("pause myDivece", null, 0, new IntPtr(0)); //pausemciSendString("stop myDivece", null, 0, new IntPtr(0)); //stopmciSendString("close myDivece", null, 0, new IntPtr(0)); //closure
Interested readers can test the examples of this article, which is believed to be of reference and helpful to everyone's C# programming.