Jan 21 2005
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):
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)