devxlogo

Play WAV Sounds from Resource Files

Play WAV Sounds from Resource Files

Everyone loves a good sound bite. You can use the PlaySound() function in the Windows Multimedia DLL (WINMM.DLL) to play a wave (WAV) file that is stored as a resource. Although you can do this using the sndPlaySound function, sndPlaySound requires you to find, load, lock, unlock, and free the resource. PlaySound achieves all of this with a single line of code.
Add this line of code to your resource file (RC) designating a name for the sound and its location:

 MySound WAVE c:musicvanhalen.wav

The name MySound is a placeholder for a name you supply to refer to this WAV resource in code.
Compile the resource file using the resource compiler (RC.EXE) to create a RES file. Include this file in your VB project. Use this code to play the sound:

 Private Declare Function PlaySound Lib _	"winmm.dll" Alias "PlaySoundA" ( _	ByVal lpszName As String, _	ByVal hModule As Long, _	ByVal dwFlags As Long) As LongPrivate Const SND_ASYNC& = &H1 ' Play asynchronously Private Const SND_NODEFAULT& = &H2' Silence if sound not foundPrivate Const SND_RESOURCE& = &H40004' Name is resource name or atom Dim hInst As Long' Handle to Application InstanceDim sSoundName As String' String to hold sound resource nameDim lFlags As Long' PlaySound() flagsDim lRet As Long' Return valuePrivate Sub Command1_Click()	hInst = App.hInstance	sSoundName = "MySound"	lFlags = SND_RESOURCE + SND_ASYNC + _		SND_NODEFAULT	lRet = PlaySound(sSoundName, hInst, lFlags)End Sub

Note that you must compile this application and run the resulting EXE directly for this code to work because it relies on the application instance handle. While in the VB development environment, App.Instance returns an instance handle to the running VB32.EXE process, not the application under development. For a complete description of PlaySound(), refer to the Multimedia section of the Win32 SDK.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist