This article will use the already established Windows API function MCISendString. The function is part of the Windows Multi-Media system in the winmm.dll using Multimedia Command Strings (MCI). WinMM is available on pretty much every modern Windows OS. Apart from having to install special codecs for uncommon audio/music formats, you can play many of the popular formats without any special setup or installation. If you want to know more about Multimedia Command strings you can check out a beginner tutorial I made at this link.
While the source code in this post is in VB.NET, you can simply change ‘as Integer‘ to ‘as Long‘. Otherwise the code should be fine.
Below is the API Function to get started.
' 'Api to send the commands to the mci device. Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" _ (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal _ uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
The next snippet is for the path to the file.
'The Chr(34) code is to put quotes at the beginning and end of the file's path. 'You can convert the long filename to the short filename and not need 'the quotes. 'That would just be more code that really isn't needed. Dim fileToPlay As String fileToPlay = Chr(34) & ("c:\MyFileToPlay.MP3") & Chr(34)
Below is a command sent to the MCI system to open and setup a new device to play the file that is specified in the fileToPlay variable.
'Let the command interface decide which device to use. Just specify the alias. 'The alias is the name you use to program that device. You can create multiple 'devices to play media at the same time and such with different alias's. MCISendString "open " & fileToPlay & " alias myDevice", vbNullString, 0, 0
The device is now setup and you just need to execute the simple commands shown below.