Tag Archives: play

How to Play an Embedded Resource .Wave Sound in VB.NET 2008, Visual Basic 2010, and Newer

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)

I’ve recenty been making an example program with Visual Basic.NET 2008 on snapping forms to the edge of the screen. I wanted the program to play a sound wave file when it performed the snapping process. But I didn’t want to have to make it link to external wave files or anything. So I decided to embed the wave sound bytes in the program itself. So this little article will show you how I went about doing that. Here is a link to the actual example application that this article is based on.

Example Playing Embedded Wave Sounds

More Info

The first thing you want to do of course is determine the wave files you want to play in your application. Remember that the size of each .wav file in bytes, willl be added to your programs file size. So remember that when you decide on what sound files you want to use.

I also want to mention that this article is specific to VB .NET 2005/2008/2010 and higher since I am using the SoundPlayer class. Visual Basic .NET 2002/2003 will have to use the PlaySound api thats part of the WinMM.dll library. The PlaySound api can play and do everything the SoundPlayer class in VB 2005 and higher can do. Just more code is involved. I actually found an article after I started this post that shows how to play wave files embedded in your VB.NET 02/03 application. Just click here to check it out.

Embedding your .Wave Files

After you have determined the wave files you want to embed in your program you need to add them to your project. There are a couple ways to do this. The easiest way is to copy your .wav file and then paste it in your project. To paste it to your project you just need to select your project name in the Solution Explorer, usually the top right panel. Then right click and click on the paste command. Another way is to click on the “Project” and click on “Add Existing Item”. Then just browse to the wave files location and select each file you want to embed. Once the files are added to your project, you will want to click on each wave file and in the properties panel (Its right below the Solution Explorer by Default). In the Properties panel you will see “Build Action”. From the build action combo list select “Embedded Resource”. Do that for each sound file you added to your project.

Playing your Embedded Files

Now that you have embedded your files into your application, its time to setup the code to play them. If your using .NET older than 2005 then check out this article on using the unManaged api call “PlaySound” to do the playback.

You now need to access your newly embedded *.wav file. You can access it as a stream under your programs manifest. Here is the method that will be used…

Public Overridable Function GetManifestResourceStream(ByVal name As String) As System.IO.Stream Continue reading

How-to Playback Movies and Videos with VB and Visual Basic .NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (25 votes, average: 4.12 out of 5)

As you will see, playing videos is easy using the Windows MCI Command interface for the playback which is supported in Windows XP, Windows Vista, Windows 7, Windows 8, and Windows 10. Specifically the MCISendString function will be used in this tutorial.

MCI should by default already support the common formats like avi, mpg, mpeg, wmv, etc. with a basic Windows installation. But you can actually get MCI to playback nearly all formats if the correct Codec/Driver is installed. For Example, you can playback Apple QuickTime .Mov, MPEG 4 DivX, or H.264 .MP4 by simply installing the codec for each format. After that just program the device like you normally would.

This article is only to show how to do basic playback of videos and not features like duration/length, position, or resizing the video. You can check out my MCI MultiMedia Tutorial to learn how to program MCI and add your own features.

If your using VB 6.0 select the correct MCISendString declare below, change any IntPtr.Zero code to 0, and use ‘.hWnd’ instead of ‘.Handle’.

Edit: 2014, December 17th: I decided to make a download available that uses all of the codes in this article with a couple extras to help resizing and such. I also changed some of the code in the program for Option Explicit.

Download Example: Click Here

View Screenshot: Click Here

Visual Basic 6.0 and Older

    'The Main API call that will be used for the playback.
    Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal _
        lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As _
            Long, ByVal hwndCallback As Long) As Long


Visual Basic.NET and Newer

    'The Main API call that will be used for the playback.
    Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal _
        lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As _
            Integer, ByVal hwndCallback As IntPtr) As Integer


OR You Can Use…

    'The main API call.
    <DllImport("winmm.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Public Shared Function mciSendString(commandString As String, returnString As String, _
        returnStringLength As Integer, _mciCallback As IntPtr) As Int32
    End Function

Now make a couple variables.

    'Will hold the path to the movie file.
    Dim filename As String

    'Holds the return value of mciSendstring. Not used for anything in this article though.
    Dim retVal As Integer


Then set a path to the file you want to play. If you’ve seen my other MCI articles you should remember about adding “Quotes” around the path and filename, or at least supply the file’s short pathname.

        'The path to the movie or video to play.
        filename = "c:\movies\MyMovieFile.mp4"

        'Now add the quotes around the path.
        filename = Chr(34) & filename & Chr(34)

Next thing to do is open and setup a playback device. I usually use the MPEGVideo device since it works with audio and video. The MPEGVideo device is DirectShow down under.

There are a couple ways you can open the video. You can have it display in its own popup window or have it displayed in a control like a Panel or Frame. Basically any control with a .hWnd or .Handle property.

This command will display open a new device and have the video display in a control window.

'This code below will open a new mpegvideo device and play the movie in the “movieWindow” control which is
'nothing more than a GroupBox/Frame control I used in an example app. Basically any control with a
'handle can be used. For VB 6 you would use the controls .hWnd property instead of the
'Handle.ToInt32 property.
'If you want MCI to select which device to use just take out "type mpegvideo" from the code.

retVal = mciSendString("open " & filename & " type mpegvideo alias myMovie parent " _
& movieWindow.Handle.ToInt32 & " style child", vbNullString, 0, IntPtr.Zero)


If you want the video to open in a separate window use this code instead.

'Specify the mpegvideo driver to play the movies which should play most movie formats without any problems.
'This code will have the video open in its Own window and the alias name will be “myMovie”.
If you want MCI to select which device to use just take out "type mpegvideo" from the code.

retVal = mciSendString("open " & filename & " type mpegvideo alias myMovie", vbNullString, 0, IntPtr.Zero)

OK, now that you’ve opened a device, all you have to do is call the Play command to begin playback. The codes below will Play, Stop, Pause, and Resume.


 'Start Playing the movie once you’ve setup the device with your file.
 retVal = mciSendString("play myMovie", vbNullString, 0, IntPtr.Zero)



'Will Stop the playback if its currently playing.
 retVal = mciSendString("stop myMovie", vbNullString, 0, IntPtr.Zero)



'Will Pause the playback if its playing.
 retVal = mciSendString("pause myMovie", vbNullString, 0, IntPtr.Zero)



'Will Resume the playback if it has been paused.
retVal = mciSendString("resume myMovie", vbNullString, 0, IntPtr.Zero)


You want to use this code when your done with your device and/or closing your program so the mci resources will be cleaned up. You could change ‘close myMovie’ and put ‘close all’ to free everything MCI has used.

        'Will make sure the previous alias is destroyed. If the alias “myMovie” hasn’t been created yet,
        'this code will NOT cause any errors or anything. So there is no need to worry about that.
        retVal = mciSendString("close myMmovie", vbNullString, 0, IntPtr.Zero)

Well, that’s all there is to it. Hope you found something useful from this article. Have Fun!


Revised: 2015

MCI MultiMedia Command String Beginners Tutorial – A Step by Step Guide for Visual Basic

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (28 votes, average: 4.29 out of 5)

I originally made this article many years ago. I tried to keep the links up to date but not with possible changes to the MCI system or better techniques. Feel free to let me know if there is anything that can be changed or improved upon by leaving a comment.

Updated 2014, December 05th & 17th: Made some minor format and wording changes.

   Overview: I made this tutorial to help others learn to use the Windows MCI (Multimedia Command Interface) system to create their own media based features or full applications like a Music Player, Movie Player, CD Player (.cda), and so on. MCI is easy to use and is able to support many of the popular file formats. For instance, you can playback: MP3 files (.mp3), Wave files (.wav), Windows Media Audio (.wma), etc… on the audio side; and MPEG4 (.mp4), AVI Video (.avi), QuickTime(.mov), Windows Media Video (.wmv) etc… on the video side. Hopefully by the time you finish this article, you will have a better understanding of the MCI system.

  Visual Basic 6.0 and other Information: While this tutorial’s example source code is in VB .NET, the principles are the same for all languages actually. C#, C++, etc.. To make much of the .NET example code work in VB 6 just change “Integer” typed variables and parameters to “Long” types instead.



With this tutorial beginners will hopefully learn how to use the Windows MCI system via the MCISendString function available in the WinMM.dll. The article does not provide much in the way of source code for special tasks or features, but aims to teach someone how to make their own. I do have a few pre-made libraries which uses MCI to do many music/movie based functions at my vbcodesource.com website.

As mentioned earlier, MCI can play almost any media file available with the proper compression decoders available. For instance, you can play DVD Movie’s If a device provides DVD decoding assistance like some video cards or Windows has a software decoder available. Likewise you can play high definition H.264 videos if you have the proper H.264 codecs, DivX Movie’s if you have the DivX Codec installed or Apple QuickTime videos if you have the QuickTime codec installed, etc.. In this tutorial I will help you get a good understanding how to program and use the MCI Device system so you would have the ability to make your own media player or add media support to your applications. As for the exercise in this tutorial I will show you how to make a music player with a few basic features. I am pretty sure though, after you read and study this article you will be able to create your own music and movie player with ease.


Lets get some Documentation

  Start out by going to: http://msdn2.microsoft.com/en-us/library/ms712587.aspx– website, then click on the: ‘Multimedia Command Strings’ link if it doesn’t go directly to that page. Go ahead and look over some of the documented MCISendString Commands available. For example: Click on the ‘open’ command at the left side of the webpage. Scroll down alittle on the right side of the page and you will see the documented device types and the device flags available for that device type. Scroll down alittle more and it will explain what the meaning of each device flag is for. For example: On the same ‘open’ page, scroll down till you find the waveaudio device listing. Look at the column to the right and you will see the available flags and the meanings that will work with the waveaudio device. Scroll down to the Value section listings of the page and find the ‘buffer buffer_size’ flag and look to the right and it explains what it is for and what it does. So, now that we’ve got that out of the way, lets get started with programming the Mci Device.

  Note: The mpegvideo device driver is not documented at the msdn webpage. We can still do quite alot with it since alot of the commands from the digitalvideo device and waveaudio device will work with the mpegvideo device. The MpegVideo device type would be the Device Driver of choice for most of our multi-media needs since it will play alot of the movie and music formats out there. The MCI system uses the functions from the ‘winmm.dll’ file. Winmm.dll is used for some of Windows own media programs.


What is the mciSendString function?

The first step you will want to do is add:

    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
  • to the declarations section of our form. The return value of the mciSendString function will be a number. It will return different numbers for different errors or return a 0 if the command was successful.

Example: Say we made a variable;

        Dim retVal As Integer


We would use our mciSendString function in this manner…

retVal = mciSendString("Open " & filename & " alias movie", 0, 0, 0)
  • retVal would contain a number returned by our Mci Device to let us know what happened. More on that below. I will briefly go over each parameter of the mciSendString function.

The lpstrCommand parameter is a string that specifys the MCI command string and flag. In other words this parameter would be our command that we pass to the MCI Device. Like in our paragraph above, open would be a command string that we passed to the MCI Device. It tells the MCI Device to do something. The command string could also have flags associated with it. More on that below in the tutorial.

The lpstrReturnString parameter is a buffer that receives the return information if requested. Example: If we used the status command string and used the position flag, lpstrReturnString would contain the position information of the music or movie we are playing. We would just create a string variable with a character buffer.


        Dim returnData As String = Space(128)

ReturnData is now a String with a 128 Space buffer.

We would put ReturnData in the parameter and it will receive our position value.

The uReturnLength parameter is the size, in characters of the lpstrReturnString parameter. If we used

        Dim returnData As String = Space(128)


– for our lpstrReturnString parameter. Then the size we would put for the uReturnLength parameter would be 128 or you can put Len(ReturnData).

The hwndCallback parameter is not used in this article. It would contain the Handle to to a callback window if the Notify flag was used in our command string. Just set this parameter to 0 for now.

Note: If the command string does not request a value in the lpstrReturnString parameter then you can set the lpstrReturnString, uReturnLength, hwndCallback parameter to “Nothing” or set to vbNullString, 0, 0). More on that further in the tutorial. 


What is mciGetErrorString?

OK, the second step you would want to do is add:

    Private Declare Function mciGetErrorString Lib "winmm.dll" Alias "mciGetErrorStringA" (ByVal dwError As Integer, ByVal lpstrBuffer As String, ByVal uLength As Integer) As Integer


– to the declarations of the form. This is a very useful function for programming the Mci Device. This will convert the number returned by our retVal variable (from the mciSendString function) into something that we will be able to understand alittle more. It will give us a brief description of what happened. I will briefly go over each parameter in this function.

The dwError parameter will contain our return value from our mciSendString function.


Say we used retVal as our variable to recieve the return value of our mciSendString function. In the dwError parameter we would put in the RetVal varaiable.

The lpstrBuffer parameter will contain the string value of our dwError parameter.

Example: Say we had

        Dim GetError As String = Space(128)


If you put GetError in the lpstrBuffer parameter, then GetErrorwould receive the error string.

The uLength parameter is the character length of the dwError parameter.

Example: Say we used the above GetError string variable. We would create the string to have a buffer of 128 characters.

        Dim GetError As String = Space(128)


So, in the uLength parameter we would put 128 or you can put Len(GetError). Either way will work just fine.


How to Write your own Audio or Music Player

  Let start doing alittle MCI Programming by making a simple mp3/wave player. Put 4 command buttons, 3 labels, and a timer on the form. With the first command button name it btnPlay set the .Text property to “Play”, the second button name btnStop and set the .Text property to “Stop”, the third button, name it btnPause and set the .Text property to “Pause”, the fourth name btnClose and set the .Text property to “Close”; name one of the labels lblPosition and will be used for the position status, name the second label lblLength and will be used for the length, and the third name lblError will be used to give us our Mci error status(Make the label fairly big because it could have a long explanation.) The timer will give the position status of the music every second, so set the interval to 1000.

  Pretty much always the first step in programming the Mci Device is starting with the open command string, since it is where we select the device type we want to use and create the alias we want to use. So go to the webpage I stated at the beginning of this tutorial and find the ‘open’ command string and click on it to read the documentation. Look over our available flags. We will want to use 2 of the flags. The type device_type(note below) and alias device_alias(note below) flag. The next step you want to do is select the file you want to play. One annoying thing about the Mci Device is that it has a hard time with long filenames, so you will either have to convert the filepath and name to the shortpath of the file or a easier and recommended way is just putting quotes around your filepath and name. The way to do this is first select the file you want to play. Then wrap the filepath and name in quotes.


        Dim fileName As String = Chr(34) & "C:MP3 Musicmysound.mp3" & Chr(34)


That will wrap the filepath in quotations. ( Chr(34) is the code for ” *Quotes* ) Of course, change the path and filename to a music file you have on your computer. Each time you use the open command, you will want to put the quotes ” ” around the file you want to play. Ok, so now that we have selected the file we want to play and put the quotes around the path, lets start programming the Mci Device. Put this in the declarations section of our form.

        'Will store our return value from the mciSendString function.
        Dim retVal As Integer

        'This variable will contain the data from the lpstrReturnString parameter. It will have a 128 character buffer.
        Dim returnData As String = Space(128)

        'Will store our return string from the mciGetErrorString function. With a buffer of 128 characters.
        Dim errorString As String = Space(128)

        'Will contain True or False if our mciGetErrorString was successful at determining our error returned
        'from the mciSendString function.
        Dim errorSuccess As Boolean


In the btnPlay button put:

        'Replace the path and filename' with file that you have.
        fileName = Chr(34) & "C:MP3 Musicmysound.mp3" & Chr(34)

        retVal = mciSendString("open " & fileName & " type mpegvideo alias oursong", vbNullString, 0, 0)


O.k. Lets break this down. Our retVal variable will contain the return value of the ‘mciSendString command’. The open command will open our fileName using the mpegvideo device type and create a alias named oursong.

*Note: The type flag can be optional. The Mci Device is usually very good about auto-selecting the correct device driver of our specified file.

*Note Again: The alias flag can also be optional. I highly recommend using it so you don’t have to keep referring to your device by the fileName variable. Just use oursong to refer to our opened device. Or any other name to refer to the device.

To see if the Mci Device was successful lets call our mciGetErrorString function. In the same command button below the code we already put in add:

        errorSuccess = mciGetErrorString(retVal, errorString, 128)


O.k. Lets break this down. Our errorSuccess variable will contain the return boolean value of our mciGetErrorString function. It will contain either “True” if it was successful or “False” if it was not successful. The retVal variable we used contains the return value from our mciSendString function.

Lets get the description of our error if one was created. In the same command button type in:

        lblError.Text = "Error Status: " & errorString


Run the program and press the “Play” button. lblError should read “The Specified Command Was Carried Out.” That means that everything went smooth and is O.K.

Now goto the webpage again and find the close command string. In the btnClose button type:

        retVal = mciSendString("close oursong", 0, 0, 0)

        errorSuccess = mciGetErrorString(retVal, errorString, 128)


O.k. Lets break this down. You should already know what the retVal variable returns. So, I won’t go over that again. What the close command does is close either a specified device identifier(Alias) or you can close all device identifiers(Alias’s) by using the all flag. So, what we just told the Mci Device to do is close our oursong device from memory. Notice that the other 3 parameters are “0” zero? Well, since the close command does not return anything we can just set the parameters to “0”. You should already know what the mciSendErrorString does so I won’t go over that again.

Now run the program again and press the play button twice. lblError should now read “The specified alias is already being used in this application. Use a unique alias.” The error string returned should be self-explanatory, but I will explain it briefly. What its saying is that the oursong alias is already opened and is being used so if we wanted to open another Mci Device we need to supply a new alias. Now press the btnClose button. lblError should now read that “The Specified Command Was Carried Out.” That means that our close command was successful at closing our oursong from memory. Now press the play button and lblError should read “The Specified Command Was Carried Out.” Press the play button again and lblError should read that “The specified alias is already being used in this application. Use a unique alias.” If you press that “Close” button lblError should read that the command was carried through. If you press that “Play” button lblError should again read that the command was carried through. Blah.. Blah.. Blah.. O.k. enough of that stuff.

Now lets program the Mci Device to play our Mp3, Wave, ect. song. Go to the webpage and select the play command and look over it. Every device type recognizes the play command string. In the “Play” button between the mciSendString code and the mciGetErrorString code that we already put their type:

        retVal = mciSendString("play oursong", vbNullString, 0, 0)


O.k. Let break this down. The play command tells the Mci Device to start playing the file contained in the ‘oursong’ alias. Pretty simple. Run the program and press the “Play” button and it should start playing the song you specified in the ‘fileName’ variable. Everything should be going well. If it isn’t check the lblError Text and see what the mciGetErrorString function is returning. Maybe while you was looking at the documentation on the play command you noticed a from position flag and a to position flag. What these 2 flags do is allow you to start playing at a certain point in the file and play to a specified point in the file. If you want to play the complete file then just ignore these 2 flags. But if you want to specify a starting point and a ending point you would program the Mci Device in this manner. (You can also specify whether to start playing the song from a specified point to the end of the song, or tell it to start from the beginning but only to a specified point.)

        retVal = mciSendString("play oursong from " & 1000 & " to " & 3000, vbNullString, 0, 0)


O.k. Lets break this down. We told the Mci Device to play ‘oursong’ from “1000 milli-seconds” to “3000 milli-seconds”. Pretty simple right? Now that we have a play command and a close command, what if you just wanted to stop the song at its current playing position and not completely close the file? Well, thats where the ‘stop’ command comes in. Go back to the msdn documentation website and click on the ‘stop’ command. Notice that their is only 1 flag available and thats for digital devices? There are no other flags we need for this command. Lets write our stop command. In the btnStop button type:

        retVal = mciSendString("stop oursong", vbNullString, 0, 0)


O.k. Lets break this down. Well, theres not much to break down. Its pretty self-explanatory. What it will do is tell the Mci Device to stop playing ‘oursong’. Not really anything more to say.

What if you wanted to add a pause command to our music player? Nothing to it. Just go to our Mci documentation website and click on the pause command. Pretty much like our stop command it doesn’t have any special flags associated with it. Lets write our pause command. In the btnPause button type:

        retVal = mciSendString("pause oursong", vbNullString, 0, 0)


O.k. Lets break this down. The ‘pause’ command is simply telling the Mci Device to stop playing oursong at the current playing position. Pretty simple. What if you wanted to resume a song that you paused with the ‘pause’ command? Nothing to it. Just go to the website and click on the ‘resume’ command and look at the documentation. Just like our ‘pause’ command their are no special flags associated with the ‘resume’ command. Put another command button on the form and name it btnResume and set the .Text property to “Resume”. Lets write our code to resume the playing of oursong.

        retVal = mciSendString("resume oursong", vbNullString, 0, 0)


O.k. Lets break this down. It is just simply telling our Mci Device to ‘resume‘ playing from where it was paused at when we used our ‘pause’ command. Nothing to it huh?

O.k. Now you have some basic functionality for your music player. Now you may want to be able to track the current position that the music is currently playing at. No Problem. Go to our documentation website and click on the ‘status’ command string. Look around on that page you see a ton of flags available with this command string. If you look at the waveaudio device you will see a position flag. That is the one we want to use to get the current position of our song. Lets write some code for it. In the timer control put:

        retVal = mciSendString("status oursong position", returnData, 128, 0)

        lblPosition.Text = "Position: " & Val(returnData)


O.k. Lets break this down. you should already know what the retVal variable is for. The ‘status’ command is telling the Mci Device that we want to get the status of oursong. But to use the ‘status’ command we have to specify a flag. So, you will have to tell the Mci Device what status information to return. We specified the position flag so, it will return the current playing position of oursong. lblPosition will contain the position value. Noticed that I used Val(returnData) for the lblPosition .Text? I did it so that lblPosition will only contain the numbers in the ReturnData string and not the remaining spaces in the buffer. Getting the hang of it now? Lets get our Mci Device to do more.

Did you happen to wonder what time format the position flag was returning to us? Well, lets have the Mci Device tell us what the answer is. Looking at our documentation webpage you should still be at the ‘status’ command string documentation. Look under either the digital video or waveaudio device type. You will see that there is a time format flag. That is the flag that we will use to get the current time format the Mci Device is using. Just draw a command button on the form and name it btnTimeFormat set the .Text property to “Time Format:”. In the code window of that button type:

        retVal = mciSendString("status oursong time format", returnData, 128, 0)



O.k. Lets break this down. We are passing the ‘status’ command string to the Mci Device and using the time format flag. This will tell the Mci Device to give us the current time format. We will get our answer by getting the value of our returnData variable. If you want you can just open the Mci Device by pressing the “Play” button and then press the “Time Format” command button. It will throw a Messagebox with the time format that the Mci Device is currently using. It most likely should say “milliseconds”. Still with me? Easier then you thought huh? What if you wanted the format in seconds? Well, the Mci Device doesn’t support returning the time format in seconds but you can easily do it yourself. 1000 milliseconds = 1 second. So, all you would need to do it create a variable to divide our Val(returnData) / 1000. The variable will contain the value in seconds. What if you wanted to get the length of the song? Well, that is just as easy as getting the position. In the “Play” command button right above our mciGetErrorString function type:

        retVal = mciSendString("status oursong length", returnData, 128, 0)

        lblLength.Text = Val(returnData)


O.k. Lets break this down. We are simply telling our Mci Device to tell us the length of oursong. Earlier we asked the Mci Device to give us the current time format and it returned “milliseconds”. So, that will be the format that our length will be returned in since we haven’t changed the time format. Can we change the time format? Yeps we sure can. Goto our Mci document page and click on the ‘set’ command string. Just like our ‘status’ command string the ‘set’ command string has a few flags available to use. The flag we want to use to change the time format would be none other than the time format flag. What you will find out though is some files, like mp3’s, the Mci Device only supports the “milliseconds” time format. If we use the mpegvideo device driver then the only available time formats would be “frames” and “milliseconds. Since we are playing music files we won’t be able to get a time format in “frames”, only “milliseconds”. If you only wanted to play wave files, for example, you could use the waveaudio device type and get the time format in “bytes”, “milliseconds”, and “samples”. I don’t think “milliseconds” is all that bad though. What else would you want to add to your music player?

Do you want to know if the music is currently playing? Would you like to change the position of the file in real time? How about a volume control? Want all 3? Well, lets get started and first write a simple function that will let our application know if it is playing or not. Write the code below in the form.

    Private Function playingStatus() As Boolean

        retVal = mciSendString("status oursong mode", returnData, 128, 0)

        If returnData.Substring(0, 7) = "playing" Then

            playingStatus = True


            playingStatus = False

        End If

    End Function


O.k. Lets break this down. We are going to use our playingStatus function to contain “True” or “False” depending on whether or not the Mci Device is playing. If you check out our documentation website and clicked the status command string. Then scrolled down you would find a mode flag available. If you read the description of the mode flag it tells you what value’s it would return. So, now to get the playing status we would just need to get the value that is stored in our ReturnData variable. But since our ReturnData variable is 128 characters long we only want to get the first 7 characters. If ReturnData contains “playing”(which is 7 characters long) then our Mci Device is currently playing and will put “True” in our playingStatus function. Other modes are available too. The device can return “stopped”, “paused”, “not ready”, ect. Right now we are only interested in checking our Mci Device to see if it is “playing” or not. Thats important for our changing the position code. Lets write that now. Put a Hscrollbar control on our form and name it posChange. Type this code in the “posChange_Scroll” sub:

        If playingStatus() Then

            ' The Mci Device is playing so play from.
            retVal = mciSendString("play oursong from " & (posChange.Value * 1000), vbNullString, 0, 0)


            ' TheMci Device is not playing so seek to.
            retVal = mciSendString("seek song to " & (posChange.Value * 1000), vbNullString, 0, 0)

        End If


O.k. Lets break this down. If you go to our documentation webpage and click on the play command string you will see a available flag named from. That is the command string and flag we will use to keep the file playing but at a position specified by our posChange.Value. If you go to our documentation website and click on the seek command string you will find a available flag named to. That is the command string and flag that we will use to move the position and but not start playing. Got that? To recap what I said above if oursong is already “playing” we will want to continue “playing” oursong but at the point in the file specified by our posChange control. So we will use the commandstringplay’ and use the flag ‘from’ to continue playing oursong “from” the position specified by our posChange control. Enough about that already. Lets move on. The Hscrollbar cannot contain a value larger than “32767”*. Since the time format of the Mci Device is in “milliseconds” and the total length of almost every song would be larger then “32767 milliseconds”* we must convert the “milliseconds” format to a smaller number. The useful and easy thing to do would be to convert it to “seconds”. So, we will set the .Max property of our Hscrollbar to equal the total length of the song in “seconds”. To do this. Let go back to the btnPlay button and type this code below our code that tells the Mci Device to “play“.

        'Get the length of the song in milli-seconds.
        retVal = mciSendString("status oursong length", returnData, 128, 0)

        'This will convert our “millisecond” value to a value in “seconds”
        'Remember that 1000 milliseconds will equal 1 second. 2000 milliseconds = 2 seconds and so on.
        posChange.Max = Val(returnData) / 1000


*Note; Update: Visual Basic.NET does NOT seem to have the .Max property of the scrollbars limited to a value of ‘32767’ as it was in VB 5.0, 6.0. So, it seems that you no longer need to worry about setting the above code up by converting the milli-seconds to seconds. It looks like it is now able to contains milliseconds with no overflow.

O.k. This should be fairly simple to understand. We are just telling the Mci Device to return the length of oursong. posChange.Max property will now contain the length in seconds (or milliseconds, its your choice as to how accurate you want to be able to change the position). We divided the number returned by our ReturnData variable by 1000 which would equal “seconds”. Got that? I hope so. Now if you go back and look at the code above to change the position you should understand it alittle more. I hope this helped you instead of confused you. I’m trying to thoroughly explain it so you will completely understand. Just as a reminder. If the code is not doing what you expected and you want to find out what is going on use the mciGetErrorString function. O.k. Enough on this. Lets do one last thing that would be useful for a basic music player. Lets create a volume control. Put a Vscrollbar control on the form and name it volScroll and set the .Max value to “1000”. “1000” is the max for the volume. “0” is the minimum. Then go to our documentation webpage and click on the setaudio command string. Look over the available flags and you will find a volume to flag. That is the command string and flag we will want to use. So in the volScroll _Scroll sub put in this code.

        retVal = mciSendString("setaudio oursong volume to " & volScroll.Value, vbNullString, 0, 0)


O.k. This should be pretty simple to understand. We are simply telling our Mci Device to set the volume of oursong to the current value of the volScroll control. Thats it for a music media player with basic features! Check out my examples and libraries at www.vbcodesource.comwebsite.

Below is the final product…




  I hope this tutorial we went over gave you a nice understanding of how to program the Windows Mci Device. As you can see there are quite a few commands and flags available to do almost anything you want in a Movie or Music player. You could “turn of the left audio channel”, “set the volume for the right audio channel”, “you could open and close the cd door”, “change the speed at which the movie or music plays at” and much more. You should be able to decide what features you want and program the Mci Device yourself and have it do it for you. Remember to use the mciGetErrorString function as it is very useful. It tells you if the device understood what you told it to do, if the Device Type that you are using supports that command string, and much more. Bookmark the msdn webpage I gave you: http://msdn2.microsoft.com/en-us/library/ms712587.aspx – so you can have it as a good reference to see what command strings and flags are available. Reference – http://www.vbcodesource.com – Have Fun!


Readymade Options for Playback of Music/Audio Files in VB and VB.NET – 1 of 2

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (10 votes, average: 3.90 out of 5)

This article and Part Two are to show some options available for Audio/Music playback if your not interested in making your own control or library. I do have an article on how to do basic music playback at this link with some quick and simple source code. But if you want more advanced features and don’t want to create the bulk of the playback code, then the content in these articles should help you out. This first article is on using some libraries I made around the MCISendString Windows API function and doesn’t have 3rd party dependency.

Note: You can now check out part two at this link on two 3rd party controls named Bass.dll and FMod.dll.

Visual Basic 6.0

For VB 6.0 is Music Module v2.2 that I made with Visual Basic 6.0 and contains the main features that a music player usually needs. It supports the most popular music formats like Wave, MIDI, and MP3 files. Some other features are calculating the MP3’s overall Bitrate, getting the Playing Position in various formats, Left/Right Volume Control with Muting, etc. While the class module is old, it still does the job well and does not rely on any 3rd Party .DLL’s or Resources. You can download the Class Module with Example at this link.

Visual Basic.NET 2002/2003

This option is basically for VB.NET 2002/2003 and would recommend you use it for those versions only. This library is called csMusicLibrary v1.0 Professional. This class contains more features than the VB 6 library.  The class has all of the features required for a normal music player and some extra features like basic playlist support, setting the music playback rate, setting the playing position and more. IF your interested in this option you can download the compiled class with example at this link.

Visual Basic 2005/2008/2010, and Higher

This next library definitely has the most features out of the options in this article. It is a major overhaul of the original csMusicLibrary. It is csMusicLibrary v3.1 – The Professional Series and made with Visual Basic 2005. It is completely XML commented with explanations about the Subs/Functions and Properties along with remarks. There are many options available and is easy to use and understand. Besides your normal playback features it can give your applications some basic recording capabilities, extract MP3 Tag v1.1 information, get the music playback status, and much more. Like the other options outlined above, this library does not rely on any 3rd party controls or resources. If you don’t need any super advanced features like visualizations, data manipulation, or sound effects, etc. then this library should work just fine for making a fully featured music application. You can download the compiled class with example at this link.

All these options should be fine for making a nice featured application. But you may be wanting more advanced features like FFT’s, Data Manipulation, Sound FX, and so on. That is where the next article will come in. Click this link to read part two about some third party controls. Have fun 🙂


Revised: 2014

Easily Play, Stop, Pause, and Resume MP3/Wav/WMA files in VB and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (31 votes, average: 3.42 out of 5)

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.
Continue reading

Play and Stop a Wave File or System Sound using VB 2005 and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)

This shows how to use Visual Basic.NET 2005, VB 2008, Visual Basic 2010, and 2013 to play a wave (.wav) file and/or play a Windows SystemSound. This uses the MY interface which uses the SoundPlayer class new to .NET 2.0.

        'This will Play a Wave file from the specified Path, Play a selected system Sound and Stop a sound that
        'is playing.
        My.Computer.Audio.Play("C:\WINDOWS\Media\Windows XP Default.wav", AudioPlayMode.Background)