Saturday, September 8, 2007

Building a CD Player in .NET

When I first started working on this project, I thought that I would build a basic cd player. I reviewed the code of many wonderful cd players that had been written in VB6. As the work progressed, however, I realized that this article could be a great tutorial to show the power of VB.NET. I developed 4 goals for the project: 1. to demonstrate how to use the Windows API function mciSendString in VB.NET, 2. to build a library of CD audio functions that could be expanded to handle other media types, 3. to build a cd player that would demonstrate most of the mciSendString capabilities, and 4. to build a button array class to use within the application. I used Visual Studio.NET to build the various parts of this application.

mciSendString

The workhorse Windows API function for cd audios is mciSendString (mci = media control interface). This function consists of 4 parameters a 'command string', a 'return string', a 'return length', and a 'handle'. The 'command string' specifies an MCI command string. This string will contain different commands depending upon what it is that you are trying to accomplish. Our CDAudio class will make use of many of the possible command string combinations. The 'return string' is a buffer that receives return information. The string is null terminated. If no return information is needed, this parameter can be NULL or 0. The 'return length' parameter is the size, in characters, of the return buffer specified by the 'return string' parameter. The 'handle' points to a callback window if the "notify" flag was specified in the command string.

mciSendString returns a zero if the action requested was successful or an error otherwise. The low-order word of the returned DWORD value contains the error return value. If the error is device-specific, the high-order word of the return value is the driver identifier; otherwise, the high-order word is zero. For a list of possible error values, see MCIERR Return Values. To retrieve a text description of mciSendString return values, pass the return value to the mciGetErrorString function. I did not add error checking to this tutorial and I leave it for you as a further enhancement.

mciSendString can be used in VB.NET with a few caveats. Data types have changed between VB6 and VB.NET and need to be coded accordingly. I replaced the long data type found in VB6 with an integer data type in VB.NET. In addition, VB.NET does not support fixed length strings which are required by the function. In order to get around this, Microsoft suggests creating a string and then filling it with spaces (see the sample below).


http://www.dotnetjunkies.com/Tutorial/C1665105-415A-4B15-839F-3F0812902B10.dcik