How to Play Embedded Resource Wav Sound in VB.NET 2005, VB 2008, and Visual Basic 2010

 
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(bites?) 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.
 
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 and higher since I am using the SoundPlayer class. That class was not added until VB 2005. Visual Basic .NET 2002 and VB.NET 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
 
You access the resource manifest through the: Reflection.Assembly.GetExecutingAssembly namespace. You have to provide the name of your programs assembly and the name of your wave file. The name of my example project is: ‘playEmbeddedWaveFileEx’ and the name of my .wav file is: ‘waveFile.wav’. Remember that your assembly and wav file IS CASE Sensitive. In other words, each letter has to be the exact upper casing and lower casing that your actual assembly and wave file is. So for my example, you would pass the assembly and wave file as: ‘playEmbeddedWaveFileEx.waveFile.wav’. Notice the . or period seperating the assembly name and the name of the wave file. An easy way of getting your assembly name is using this Property: My.Application.Info.AssemblyName. First is the code for literally specifying the name of your assembly. So you pass it to the GetManifestResourceStream’s parameter like below…
 
Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(“playEmbeddedWaveFileEx.waveFile.wav”)
 
BUT a better way…
 
Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(My.Application.Info.AssemblyName & “.waveFile.wav”)
 
 

Now all you have to do is create a new SoundPlayer or access the Soundplayer under the ‘MY’ interface and pass the stream and simply start playing the wavefile like below…
 

        '
        'This creates a new instance of the SoundPlayer class while passing the stream the wave file
        'is embedded in.
        '
        Dim audioPlayer As New Media.SoundPlayer(Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream( _
            My.Application.Info.AssemblyName & ".waveFile.wav")) ' "playEmbeddedWaveFileEx.waveFile.wav"))

        audioPlayer.Play()

 
OR you can use the MY Interface…
 

        '
        'This code uses MY, which basically makes it a touch easier since you want have to create
        'a instance of the SoundPlayer class.
        '
        My.Computer.Audio.Play((Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream( _
            My.Application.Info.AssemblyName & ".waveFile.wav")), AudioPlayMode.Background)

 
___________________
 
Remember that I have a example program on how to perform the steps in this article. Click here to download.

OK, so playing embedded wave files isn’t as straight forward perhaps as it should be. I think I found out about using the GetManifestResourceStream at vbforums.com. If you know of something better definitely leave a comment. Either way, the code I provided here DOES work. At least for me. :) Have fun!

Jason

Playback Music/Audio Files in VB and VB.NET (#2 – 3rd Party Libraries) – #2 of 3

 
  Well its been somewhat a long time coming but I finally got the time to add #2 of the ways to play music articles using Visual Basic and Visual Basic .NET 2002/2003 and Visual Basic 2005/2008. This post is basically to describe two different librarys. The first is Bass.Dll and the second is FMod.dll.

   

  Both of these librarys are Free as long as your application that is using them are NOT commercial or compensated. So if its a Freeware application or personal application they will grant you a license to use them. Bass.dll has a lower cost option if your making a Shareware app though. You will definitely need to read through the license agreements of each library before using them in your applications.

    

   

________________________________

    

   

BASS.DLL Audio Library

    

  This is a very nice library for pretty much all of your music or audio needs. It plays everything from mp3’s to waves and mod music. It has alot of source code and examples for Visual Basic and Visual Basic.NET. This library even gives you access to the samples that are playing so you can plot your own visualizations or ffts. I’ve had alot of experience with this library a couple years ago and even made the original VB.NET api and examples for the author. The .dll is very small in size (Under 100KB) so it won’t bloat your application.

   

Author Information: BASS is an audio library for use in Windows and Mac OSX software. Its purpose is to provide developers with powerful and efficient sample, stream (MP3, MP2, MP1, OGG, WAV, AIFF, custom generated, and more via add-ons), MOD music (XM, IT, S3M, MOD, MTM, UMX), MO3 music (MP3/OGG compressed MODs), and recording functions. All in a tiny DLL, under 100KB* in size.

   

On Windows, BASS requires DirectX 3 or above for output, and takes advantage of DirectSound and DirectSound3D hardware accelerated drivers, when available. On OSX, BASS uses CoreAudio for output, and OSX 10.3 or above is recommended. Both PowerPC and Intel Macs are supported.

   

C/C++, Delphi, Visual Basic, and MASM APIs are provided, with several examples to get you started. .Net and other APIs are also available.

   

 Main features 
Samples
Support for WAV/AIFF/MP3/MP2/MP1/OGG and custom generated samples
Sample streams
Stream any sample data in 8/16/32 bit, with both “push” and “pull” systems
File streams
MP3/MP2/MP1/OGG/WAV/AIFF file streaming
Internet file streaming
Stream data from HTTP and FTP servers (inc. Shoutcast, Icecast & Icecast2), with proxy server support and adjustable buffering
Custom file streaming
Stream data from anywhere using any delivery method, with both “push” and “pull” systems
Multi-channel streaming
Support for more than plain stereo, including multi-channel OGG/WAV/AIFF files
MOD music
Uses the same engine as XMPlay (very accurate, efficient, high quality reproduction), with full support for all effects, filters, stereo samples, DMO effects, etc…
MO3 music
MODs with MP3 or OGG compressed samples (vastly reduced file size with virtually identical sound quality), MO3s are created using the MO3 encoder
Multiple outputs
Simultaneously use multiple soundcards, and move channels between them
Recording
Flexible recording system, with multiple device support and input selection, (WMA encoding & broadcasting via the add-on, and other formats via BASSenc)
Decode without playback
Streams and MOD musics can be outputted in any way you want (encoded, written to disk, streamed across a network, etc…)
Speaker assignment
Assign streams and MOD musics to specific speakers to take advantage of hardware capable of more than plain stereo (up to 4 separate stereo outputs with a 7.1 soundcard)
High precision synchronization
Synchronize events in your software to the streams and MOD musics, synchronize playback of multiple channels together
Custom DSP
Apply any effects that you want, in any order you want
DirectX 8 effects Windows only
Chorus / compressor / distortion / echo / flanger / gargle / parametric eq / reverb, 2 implementation options each with its benefits (including mixing with DSP functions)
32 bit floating-point decoding and processing
Floating-point decoding/rendering, DSP, FX, and recording
3D sound
Play samples/streams/musics in any 3D position, with EAX support
Flexible
Small buffers for realtime performance, large buffers for stability, automatic and manual buffer updating, configurable threading
Expandable
Add-on system for additional format support and effects (C/C++ API available on request), dynamic plugin loading system, access to underlying DirectSound objects
Small
BASS is less than 100KB*, so won’t bloat your distribution

    

  As you can see, this is a very powerful and flexible sound system. If your interested in this .dll then go to the main audio librarys webpage.

    

   

 _______________________________

   

   

FMOD Music and Sound Effects System

   

  This is another very popular sound system that is used by game makers and the like. Crysis is a newer game that uses this library. This library has been around for a very long time and has matured quite a bit. It has nearly all the features you’ll ever need in a sound system. It plays most all of the common music formats as well. This library I guess would be considered a competitor to the Bass library above. The library has Visual Basic based APIs and Examples as well. I am not completely sure about Visual Basic.NET though. I don’t have much experience with this sound system like I do with the Bass sound system. Below is some author information…

   

Author Information: FMOD Products

   

Why choose FMOD?

 

FMOD supports more hardware platforms than any other audio system – including the latest ‘next gen’ consoles. Consider the cost savings of not having to change code across any platform – Save months of development time.

FMOD is actively developed, with regular releases of new features. Many new requested features have been provided to customers in a very short turnaround – want a new feature, just ask!

Many customers are amazed at the personal level of technical support they get, either by phone, email or even personal visit (if applicable)

    

 

Key features:

 

  • Fantastic sounding DSP audio engine
  • Choice of low-level API or data driven API
  • Built-in DSP effect suite and VST support
  • Advanced features such as 2D/3D morphing
  • 3D reverb support and geometric occlusion
  • Performance optimized for each platform
  • Comprehensive technical support  

     

If your wanting more information about this library you can click this link to their website.

    

   

_______________________________

   

   

  Well, thats all for Part #2 of this article series. Hopefully this post was useful or helpful to you in some way. Remember to always read the librarys license agreements before using them in your applications. They both allow free use in a free application. Otherwise you will need to buy a license if your using them in a commercial application.

   

  I will put up Part #3 when I get the chance. Part three will be on using the Windows API to do some audio or music based playback using the VB languages. Till then, Have Fun!

   

                 Jason

Playback Music/Audio Files in VB and VB.NET (#1 – My Pre-Made Libraries) – #1 of 3

Intro…

There are no doubt many requests at various messageboards and sites with VBers wanting to play MP3, Wave, ect… based files, sound effects and visualizations. This article is simply to help ‘lead’ you in the right direction to accomplish this. I do have a simple article on this site on how to do very basic music playback making your own playback codes at this link. But IF you want more advanced features and especially don’t want to create your own playback codes, then the content in the Three (3x) articles should help you out. The library’s in this first article were made by me and are available at my sister site: http://www.vbcodesource.com. All of the librarys have examples available and you can get the source code to most of them as well.

Option #1: Music Module; csMusicLibrary; = Centered Around the Windows API = No 3rd Party Dependence

    

Visual Basic 5.0/6.0…

A viable option for VB 5.0/6.0 is from my website at: http://www.vbcodesource.com. The Music Module v2.2 was made for Visual Basic 5.0/6.0 and contains the main features that a music player usually needs. IT supports the most popular music formats including, Wave and MP3 files. Some of the features is calculating the MP3’s Bitrate, Playing Position in Various Formats, Left/Right Volume Control and Muting. While the library 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 from this page. A example of using the library is at this page.

Visual Basic.NET 2002/2003/2005/2008…

There are likewise some options that I made to be used with the Visual Basic.NET versions. This option is called csMusicLibrary v1.0 Professional. Like the VB 6 class module above, this library is based around the Windows API. So it does NOT rely on any third party resources or files. This library actually contains more features than the VB 5/6 library and works with ALL versions of .NET up to even Version 2008. But I originally made it for VB.NET 2002/2003 and would recommend you use it for those versions. This library has all of the features required for a normal music player and some added content like basic playlist support, setting the music playback rate, setting the playing position and more. IF your interested in this library, then just head over to this link to get it which is the source code. A example of this library is available at this page.

Visual Basic 2005/2008 Only

This next library is definitely the Ultimate out of the options in this first article. It is a Major overhaul of the original csMusicLibrary. It is called csMusicLibrary v3.1 – The Professional Series. It is completely XML commented with explanations about the Subs/Functions and Properties along with other remarks. There are MANY options available and is hopefully easier to use and understand. Besides your normal playback features it can give your applications basic recording capabilities, extract MP3 Tag 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 your going to be using Visual Basic 05 or VB 08, and do not need any super advanced features like visualizations, data manipulation, sound effects, ect.. then this library should work just fine to build a fully featured music application.

Summary…

The options on this page can play most of the popular music formats like MP3, Midi, WMA, ect.. But the library’s can be expanded to play other formats if the proper Codecs are installed. But the options outlined in this first article are obviously missing alot of avanced features. That is where the next Two (2x) articles will come in. They will be added when time becomes available. The next 2x options WILL be 3rd Party based and costs money if you want to use it in a Commercial based application. But, IF your app is freeware, then they are completely free. Anyways, all of the articles will be very simple and alot of people won’t even find any of it useful. But for those that will, I hope the articles will end up leading you in the right direction. The next 2x articles will hopefully be up very soon. Have fun :)

Jason

How you can Play Wave Files Easily with VB 6.0 and 5.0

Playing Wave files with Visual Basic Classic (5.0/6.0 versions) is quite easy using the Windows APIs. The API you would be interested in using to play wav files is the: PlaySound – API Call. Below is the Constants and Function which should be put in a Module or Declaration section of your project…

   '
    'These Constants and API call was copied from the API-Guide program.

    Private Const SND_APPLICATION = &H80 ' look for application specific association

    Private Const SND_ALIAS = &H10000 ' name is a WIN.INI [sounds] entry

    Private Const SND_ALIAS_ID = &H110000 ' name is a WIN.INI [sounds] entry identifier

    Private Const SND_ASYNC = &H1 ' play asynchronously

    Private Const SND_FILENAME = &H20000 ' name is a file name

    Private Const SND_LOOP = &H8 ' loop the sound until next PlaySound

    Private Const SND_MEMORY = &H4 ' lpszSoundName points to a memory file

    Private Const SND_NODEFAULT = &H2 ' silence not default, if sound not found

    Private Const SND_NOSTOP = &H10 ' don't stop any currently playing sound

    Private Const SND_NOWAIT = &H2000 ' don't wait if the driver is busy

    Private Const SND_PURGE = &H40 ' purge non-static events for task

    Private Const SND_RESOURCE = &H40004 ' name is a resource name or atom

    Private Const SND_SYNC = &H0 ' play synchronously (default)

    Private Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" (ByVal _
lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long

_____________________________

   

    

Below is how to use the Playsound function to play a wave file…

'
'This will simply play a wave sound from a file location and aSync so it uses
'a thread other than  your applications thread and will not keep your application
'from responding till its done, like playing Sync would do.
'
'The flag: SND_FILENAME I believe is the default for the PlaySound function.
'You can execute'that flag if you want to make sure it plays the sound file fine.
'
PlaySound("c:\windows\media\tada.wav", 0, SND_ASYNC)
'
'
'IF you want to use more than 1x flag with the api call, then just call it like below....
'
'This will play a wave file async and loop it over and over till you call the PlaySound
'Function again.
PlaySound("c:\windows\media\tada.wav", 0, SND_ASYNC Or SND_LOOP)

And that all there is to it to call and use the Playsound function to play a wave file. But what if you wanted to stop a wave file that is already playing? That is taking care of below…

'
'This will call the Playsound function to execute and play nothing which will interupt and stop the previous wave file from playing.

PlaySound(vbNullString, 0, 0)

_____________________________

   

   

And that is all you have to do to play wav sound files with Visual Basic 5.0 and Visual Basic 6.0. Hope you found something useful :)

Jason

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

There are many paths you can take. 3rd Party librarys, Windows Media Player component, Windows API and more. The answer i’m going to give is using the already established Windows APIs.

The APIs are connected to the Windows Multi-Media System. Or winmm.dll. This multi-media system is installed on every modern Windows OS. So, apart from having to install special codecs for uncommon formats, you can play many of the popular formats without any special setup or installation. Anyways, below is the API 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

With this API you can do a great deal of playback and even some recording features for your applications. This article is meant to be very simple and a basic starting point only. But if your interested to learn more about this mciSendString interface, then goto my website: http://www.vbcodesource.com under the VB.NET Tutorials Page, and download my mciSendString Tutorial which goes in-depth using these APIs. You can also goto this Microsoft link to access the reference for this API: http://msdn2.microsoft.com/en-us/library/ms710815.aspx . You can also goto my website and download one of my full-featured librarys. Lets get started on the purpose of this answer article.

Below is a command sent to the MCI system to open and setup a new device to play the sound that is specified as the path…

'Put " and " at the beginning and end of the filename and path. The device
'could fail without 'these quotes. 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 AsString

fileToPlay = Chr(34) & ("c:\MyFileToPlay.MP3") & Chr(34)

 

The variable above will contain the filename you want to play.

———————————————————————————————–

Now setup and load the device with the file that is specified in the fileToPlay example 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", Nothing, 0, 0)

 

The device is now setup and you just need to send the command for mci to play your file.

——————————————————————————————–

mciSendString(“play customAlias”, Nothing, 0, 0)

The command above will start playing the mp3/wav/wma or whatever file you specified in the fileToPlay variable.

————————————————————————-

You can also setup the device to stop and/or pause/resume the playback of your media. as shown below….


mciSendString("stop myDevice", Nothing, 0, 0)

mciSendString("pause myDevice", Nothing, 0, 0)

mciSendString("resume myDevice", Nothing, 0, 0)

And this is all you have to do to get quick, and easy playback in your Visual Basic 5.0/6.0; Visual Basic.NET 2002/2003; Visual Basic 2005, VB 2008, and VB 2010 applications! I do hope you get something useful from this small answer article. :)

Jason

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

This shows how to use Visual Basic.NET 2005, VB 2008, and Visual Basic 201 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)

        My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep)

        My.Computer.Audio.Stop()