How to use resources file to store and play wav media file in

In this article, we will learn how to use .resources file to store .wav media file. You can use that .resources file into your project, and can play that .wav file programmatically.

Create resources file and add .wav file

You can use the System.Resources.ResourceWriter class to programmatically create a binary resource (.resources) file directly from code and add the resources as wav file.For it first we create a byte array from the the selected wav file. and then we use AddResources method to store the file in the resources file.

 Private Sub AddResources()
        Dim sndResource As Byte()
            sndResource = System.IO.File.ReadAllBytes("C:\MyMedia.wav")
        Catch ex As Exception
        End Try
        Using rw As New ResourceWriter("CarResources.resources")
            rw.AddResource("Media1", sndResource)
        End Using
    End Sub

After execute code MyMedia.resources file will be created in the application execution path.

Play sound:

And you can also play sound Embedded in a Resource at runtime. for it we are ResourceReader class to read the resources file. below code shows how we can read the wav file and play.

 Private Sub PlayFileFromResources()
        Dim resoReader As ResourceReader = New ResourceReader("MyMedia.resources")
        Dim REResource As Byte()
        Dim dEnum As IDictionaryEnumerator = resoReader.GetEnumerator()
        While dEnum.MoveNext()
            Select Case dEnum.Key
                Case "Media1"
                    REResource = dEnum.Value
            End Select
        End While
        Dim st As IO.Stream = New IO.MemoryStream(REResource)
        Dim player As SoundPlayer = New SoundPlayer(st)
    End Sub