Jan 10 2006

Playing a wav resource in VB.NET 2.0

Published by at 1:24 pm under .NET

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.

I happened across this file quite by accident but it seems that it will greatly simplify the code that was required for .Net 1.1.  The code for .Net 2.0 looks something like:

Imports System
Imports System.Media
Imports System.Resources
Imports System.Reflection
Imports System.IO

Public Class Sound
    Public Shared Sub PlayWavResource(ByVal wav As String)

        ' get the namespace	
        Dim strNameSpace As String = Assembly.GetExecutingAssembly()_
                                    .GetName().Name.ToString()

        ' get the resource into a stream
        Dim resourceStream As Stream = Assembly.GetExecutingAssembly()_
                                     .GetManifestResourceStream(strNameSpace + "." + wav)
        If resourceStream Is Nothing Then Exit Sub

        With New SoundPlayer(resourceStream)
            .PlaySync()
        End With
    End Sub
End Class

As you can see we no longer require the calls to the Win32 API. Whilst this may not mean much to the average Joe Bloggs, it is rather important. It means that we can now play wavs from a resource stream without breaking out of managed .Net code…. I knew you’d be excited by that!!!

Note: I haven’t tested this code yet. This is only code dervied from looking through the Object Browser in Visual Studio 2005.  If you copy and paste this code you will also need to re-type the single and double quotes as WordPress screws them up.

No responses yet