user2396186 user2396186 - 18 days ago 8 Question

mciSendString/winmm.dll - Playing an Audio file

I am working on a program in Visual Basic 2008, I am required to have different types of sounds with varying volumes. Hence My.Computer.Audio.Play is not a valid option.

I decided to use mciSendString instead and found the following code

Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" _
(ByVal lpstrCommand As String, ByVal lpstrReturnString As String, _
ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer

mciSendString("close myWAV", Nothing, 0, 0)
Dim fileName1 As String =
mciSendString("open " & fileName1 & " type mpegvideo alias myWAV", Nothing, 0, 0)
mciSendString("play myWAV", Nothing, 0, 0)

'min Volume is 1, max Volume is 1000
Dim Volume As Integer = (SFXVolume * 100)
mciSendString("setaudio myWAV volume to " & Volume, Nothing, 0, 0)

Now this code I have tested and is working perfectly when filename1 = "C://Correct.wav"

However when I use

filename1 = My.Application.Info.DirectoryPath & "\Correct.wav"

I get no sound play whatsoever.

Could anyone please help me correct my code so that this works.
Thank you in advance.


If your DirectoryPath has spaces then mciSendString won't be able to recognize the command accurately, you need to surround the path with quotes:

    String.Format("open ""{0}"" type mpegvideo alias myWAV", fileName1), Nothing, 0, 0)

Be sure to check returned status as well, as Hans suggests.

Also, since you don't know whether DirectoryPath has a trailing backslash or not, the accurate way to produce full path from directory and name is:

fileName1 = System.IO.Path.Combine(My.Application.Info.DirectoryPath, "Correct.wav")