Jan 21 2005
Playing a wav from a resource in VB.NET
This is a little code snippet that will allow you to play wav files that are embedded in your VB.NET exe. This code is based on a C# class by Peter A. Bromberg that I found on this page.
I had to do a little reworking to get it to play with VB.NET. ANd my VB code probably isn’t the neatest way that it could be done… but it works.
Imports System Imports System.Runtime.InteropServices Imports System.Resources Imports System.IO
Public Class Sound
Private Shared SND_ASYNC As Integer = 1 Private Shared SND_MEMORY As Integer = 4
Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" (ByVal lpszName As Byte(), ByVal hModule As Integer, ByVal dwFlags As Integer) As Integer
Public Shared Sub PlayWavResource(ByVal wav As String)
' get the namespace Dim strNameSpace As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString()
' get the resource into a stream Dim resourceStream As Stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(strNameSpace + "." + wav) If resourceStream Is Nothing Then Exit Sub
' bring stream into a byte array Dim wavData As Byte() ReDim wavData(CInt(resourceStream.Length)) resourceStream.Read(wavData, 0, CInt(resourceStream.Length))
' play the resource PlaySound(wavData, 0, SND_ASYNC Or SND_MEMORY) End Sub End Class>>
do to user this code is create a new VB.NET class file and paste this code in. When you want to play a wav you must include the wav file in your project as an embedded resource and use the following (replacing the name of the wav file to be played):
Sound.PlayWavResource("chimes.wav")
Please note that the Sound class must be in the same assembly as the the wav file.
Update: Please copy the source code and paste it into a texteditor to read it as the code has been broken onto multiple lines on this page by my blog stylesheet.
Update 2: Yes I know its got the same comments as the page I referenced above. Give me a break, its 8pm on a Friday and I’m still at work. What more do you want? For me to translate the bible into Haxxor?
Update 3: I’ve just corrected a couple of errors in the above code (removed a > and removed an extra End If)


This is the neatest way to play a sound from memory that I have found posted anywhere. Thanks.
Thank you for the comment but I really must say that the work was done by Peter Bromberg. I just took his C# code and translated it into VB.Net
[...] 1:24 pm This is a follow-up to my previous post “Playing a wav from a resource in VB.Net“. The previous post was how to get it working in VB.Net for the .Net Framework 1.1. In the .Net Framework 2.0, Microsoft has been kind and provided a System.Media namespace in the core System.dll. [...]
Software Development Guide…
I couldn’t understand some parts of this article, but it sounds interesting…
there is an error occurs that ” Object reference not set to an instance of an object.” please help me…….