none
Play sound doesn't work in vb.net RRS feed

  • Question

  •  i am trying to use  My.Computer.Audio.Play("location of file ") to play a sound , but it doesn't work 

    i am using visual studio 2017   is there any settings i should make or a reference i should add or what the problem is 

    Sunday, August 27, 2017 3:08 PM

Answers

  •  I found the solution in other page  

    thank yoo all anyway and i will put the solution here to help other people who may face the same problem . please note to change the file name to the file you want to play

    Option Strict On
    
    Public Class Form1
    
        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
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.CenterToScreen()
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Try
                mciSendString("close myWAV", Nothing, 0, 0)
    
                Dim fileName1 As String = "C:\Users\John\Music\The Cars\The Cars - Heartbeat city.wav"
                mciSendString("open " & ChrW(34) & fileName1 & ChrW(34) & " type mpegvideo alias myWAV", Nothing, 0, 0)
                mciSendString("play myWAV", Nothing, 0, 0)
    
                Dim Volume As Integer = 1000 ' Sets it to use entire range of volume control
                mciSendString("setaudio myWAV volume to " & Volume.ToString, Nothing, 0, 0)
    
            Catch ex As Exception
                Me.Text = ex.Message
            End Try
        End Sub
    
    End Class


    • Edited by AmerZam Saturday, September 23, 2017 6:37 PM
    • Marked as answer by AmerZam Saturday, October 7, 2017 5:32 PM
    Saturday, September 23, 2017 6:36 PM

All replies

  •  i am trying to use  My.Computer.Audio.Play("location of file ") to play a sound , but it doesn't work 

    i am using visual studio 2017   is there any settings i should make or a reference i should add or what the problem is 

    Hi

    I use the following:

    Imports System.Media

    and declarations:

        Public TopClick As SoundPlayer = New SoundPlayer(My.Resources.TopClick)
        Public BottomClick As SoundPlayer = New SoundPlayer(My.Resources.BottomClick)
        Public GameOver As SoundPlayer = New SoundPlayer(My.Resources.GameOver)
    
    '  ....... with others 

    to use:

    If My.Settings.CumScore + Score > 0 Then
        Lost.Play()
    Else
        GameOver.Play()
    End If


    Regards Les, Livingston, Scotland


    • Edited by leshay Sunday, August 27, 2017 3:21 PM
    Sunday, August 27, 2017 3:20 PM
  •  i am trying to use  My.Computer.Audio.Play("location of file ") to play a sound , but it doesn't work 

    i am using visual studio 2017   is there any settings i should make or a reference i should add or what the problem is 

    And you use a WAV file? That is the only format that goes with this. Don't think you are the first one who use that kind of things. There have hundred of thousand gone before you.


    Success
    Cor


    Sunday, August 27, 2017 4:21 PM
  • This works for me. I guess you changed the path "location of file " to the .wav file location on your system?

            My.Computer.Audio.Play("C:\test sounds\w_hwy.wav")

    Sunday, August 27, 2017 5:25 PM
  • Hi , i thought the same , but  the location is ok and the file is ok  ,, i even tried to urn the file using (windows button & R )  and input the location , it worked perfectly  

    i used to run it  with my previous laptop but now  its not working   my previous laptop was 64 * 64 and my current is 64*32

    is it making any difference ?


    • Edited by AmerZam Sunday, August 27, 2017 5:52 PM
    Sunday, August 27, 2017 5:50 PM
  • Thank you , but it didn't work

    i even tried to declare the following 

      Public Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long

    and to play , i used the below code

        PlaySound("D:\TICKETS\En-voice\11.wav", 0, &H0)

    it also didnt' work 

    • Edited by AmerZam Sunday, August 27, 2017 5:54 PM
    Sunday, August 27, 2017 5:51 PM
  • yes wav file 

    and didn't work

    Sunday, August 27, 2017 5:53 PM
  • yes wav file 

    and didn't work

    Can you show the whole method (sub or function) where you have placed this code. Because if it is on a wrong place it never will what you call work. 

    Success
    Cor


    Sunday, August 27, 2017 6:23 PM
  • Hi

    Sounds (no pun intended) that there is something else in your code that is causing your sounds to fail.

    Suggest you try building a small test project to prove/disprove that sound will/will not actually play.

    If they do play OK then look to your original code and see why!


    Regards Les, Livingston, Scotland

    Sunday, August 27, 2017 6:28 PM
  • thank you  , i just did the same   and i even tried to use two ways to play sound  but it didn't work 

        

     Public Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long


        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

            MsgBox("hi")


            PlaySound("D:\TICKETS\En-voice\11.wav", 0, &H0)
            My.Computer.Audio.Play("D:\TICKETS\En-voice\11.wav")
        End Sub

    above is what i used  

    Sunday, August 27, 2017 6:57 PM
  •   sure  , you can see below the two ways i tried to play the sound

     Public Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long


        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

            MsgBox("hi")


            PlaySound("D:\TICKETS\En-voice\11.wav", 0, &H0)
            My.Computer.Audio.Play("D:\TICKETS\En-voice\11.wav")
        End Sub

    thank you 

    Sunday, August 27, 2017 6:58 PM
  • Hi

    Put a breakpoint on the first sound line PlaySound("D:\TICKETS ...... and see firstly that it reaches the breakpoint and secondly, step one line and see if it passes the line without error.

    Then do same with second sound line.

    BTW: use the code block tool when you post code. (from the toolbar)


    Regards Les, Livingston, Scotland

    Sunday, August 27, 2017 7:07 PM
  •  I found the solution in other page  

    thank yoo all anyway and i will put the solution here to help other people who may face the same problem . please note to change the file name to the file you want to play

    Option Strict On
    
    Public Class Form1
    
        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
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.CenterToScreen()
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Try
                mciSendString("close myWAV", Nothing, 0, 0)
    
                Dim fileName1 As String = "C:\Users\John\Music\The Cars\The Cars - Heartbeat city.wav"
                mciSendString("open " & ChrW(34) & fileName1 & ChrW(34) & " type mpegvideo alias myWAV", Nothing, 0, 0)
                mciSendString("play myWAV", Nothing, 0, 0)
    
                Dim Volume As Integer = 1000 ' Sets it to use entire range of volume control
                mciSendString("setaudio myWAV volume to " & Volume.ToString, Nothing, 0, 0)
    
            Catch ex As Exception
                Me.Text = ex.Message
            End Try
        End Sub
    
    End Class


    • Edited by AmerZam Saturday, September 23, 2017 6:37 PM
    • Marked as answer by AmerZam Saturday, October 7, 2017 5:32 PM
    Saturday, September 23, 2017 6:36 PM
  •  I found the solution in other page  

    Since you appear satisfied with the last solution you posted, the code in your
    earlier attempts need not be investigated further. It seems likely that the
    failures were due to the type of file you were trying to play.

    I don't see where you described *exactly* what was happening when you tried
    PlaySound, etc. You just said "it doesn't work" without elaborating. It's
    important in such cases to be very specific, as "doesn't work" could mean
    just about anything.

    For the benefit of others who might wish to try using your earlier code
    examples to play .wav files, I feel I should point out a change that may
    be needed when using the .NET versions of Visual Basic. The signature you used:

    Public Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" _
     (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) _
     As Long

    appears to have been taken from an example used with VB6. If it is used with
    any version of VB .NET then "Long" must be replaced with "Integer". Failure
    to do so will result in stack corruption, as Long is 64-bits in VB .NET and
    32-bits in VB6. The PlaySound function in winmm.dll expects 32-bit arguments
    and return.

    - Wayne

    Sunday, September 24, 2017 7:05 AM
  •  Just some side notes...

     In your open command you are describing the device type as "type mpegvideo".  That should be "type waveaudio" if you are opening a (.wav) audio file.  However,  you can leave it out of the command all together and the correct type will be used automatically.  It will go by the filename's extension (.wav) which it knows is a wave audio type.  For example...

    mciSendString("open " & ChrW(34) & fileName1 & ChrW(34) & " alias myWAV", Nothing, 0, 0)
     

     Also,  it would make more sense to set the volume of the device before you play the wave audio file with it...

                Dim fileName1 As String = "C:\Users\John\Music\The Cars\The Cars - Heartbeat city.wav"
                mciSendString("open " & ChrW(34) & fileName1 & ChrW(34) & " type mpegvideo alias myWAV", Nothing, 0, 0)
    
                Dim Volume As Integer = 1000 ' Sets it to use entire range of volume control
                mciSendString("setaudio myWAV volume to " & Volume.ToString, Nothing, 0, 0)
    
                mciSendString("play myWAV", Nothing, 0, 0)

     

     One last note is that the mciSendString function will not throw an exception so,  there is no need for putting it in a Try/Catch.  With mciSendString you need to test the Return value of the function in order to catch any errors that happen.  As the msdn documents state,  the function will return 0 if it succeeds or an error code if it does not.  For example,  to make sure the file was opened without error before playing it...

        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            mciSendString("close myWAV", Nothing, 0, 0)
    
            Dim fileName1 As String = "C:\Users\John\Music\The Cars\The Cars - Heartbeat city.wav"
    
            Dim ret As Integer = mciSendString("open " & ChrW(34) & fileName1 & ChrW(34) & " alias myWAV", Nothing, 0, 0)
    
            If ret = 0 Then
                Dim Volume As Integer = 1000 ' Sets it to use entire range of volume control
                mciSendString("setaudio myWAV volume to " & Volume.ToString, Nothing, 0, 0)
    
                ret = mciSendString("play myWAV", Nothing, 0, 0)
                If ret <> 0 Then
                    MessageBox.Show("Error playing the file. Error Code: " & ret.ToString("X"))
                End If
    
            Else
                MessageBox.Show("Error opening the file. Error Code: " & ret.ToString("X"))
            End If
        End Sub


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Sunday, September 24, 2017 11:45 AM
    Sunday, September 24, 2017 11:44 AM
  • thank you ..

    i  still have a problem of playing many files (one after the other )  it only plays the last file 

    Any Idea about how to play many files  or help me with PlaySound("D:\TICKETS\En-voice\11.wav", 0, &H0)

    i used to use it to play many files with no problems , but now i am having a problem with it as i mentioned earlier 


    Sunday, September 24, 2017 5:33 PM
  • thank you ..

    i  still have a problem of playing many files (one after the other )  it only plays the last file 

    Any Idea about how to play many files ...

     I don`t know if i understand correct.  Do you want to play one file until it ends,  then open and play the next audio file until it ends,  and so on....  Or do you want to play multiple audio files at the same time,  like having a background music file playing in a game at the same time you have other game sound effects playing.

     Below is a link to a thread that i posted a small example of a class called MultiSoundPlayer that uses the mciSendString function.  You can use it to open several audio files and play them at any time,  overlapping two or more sounds or not.  It also allows you to use it's SoundEnded event so you can tell which sound is ending and play it again,  basically a looped sound.  You could also use the event to start playing the next audio file.

    How to play sounds not in background?

     I will get back about the PlaySound function,  i have to go eat dinner.  However,  i am starting to think that the audio file is the culprit in all this.  You have not said much more than "it does not work" which does not give us any help in finding the problem.  The audio file seems to be the only thing that stays the same in all these problems.


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Monday, September 25, 2017 8:39 PM
    Sunday, September 24, 2017 8:07 PM
  • ....  or help me with PlaySound("D:\TICKETS\En-voice\11.wav", 0, &H0)

    i used to use it to play many files with no problems , but now i am having a problem with it as i mentioned earlier 

     As i believe has been mentioned already,  you where using a signature of the function that was meant for VB6.  In Vb.Net,  the parameters are declared as different types than Longs.  You can see the difference in the parameter types in example below.

     This is just a basic example that should work for you,  however,  the others should have worked too.  Create a new form project with 1 button added to the form.  Then copy/paste this code,  changing the file path and name of coarse.

     This example uses the SND_ASYNC flag to play it asynchronously.  That means that the function returns immediately and the rest of the code after it runs while the sound is playing.

    Imports System.Runtime.InteropServices
    
    Public Class Form1
        Private Const SND_SYNC As Integer = &H0
        Private Const SND_ASYNC As Integer = &H1
        Private Const SND_NODEFAULT As Integer = &H2
        Private Const SND_LOOP As Integer = &H8
        Private Const SND_FILENAME As Integer = &H20000
    
        <DllImport("winmm.dll", EntryPoint:="PlaySoundW")>
        Private Shared Function PlaySoundW(<MarshalAs(UnmanagedType.LPWStr)> ByVal pszSound As String, ByVal hmod As IntPtr, ByVal fdwSound As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean
        End Function
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim filename As String = "C:\Test\Sounds\GemPopped.wav"
            PlaySoundW(filename, IntPtr.Zero, SND_FILENAME Or SND_ASYNC)
            MessageBox.Show("This message will show at the same time the file is playing")
        End Sub
    End Class
    


     

     Here is the same example but,  it uses the SND_SYNC flag so that the function will not return and execute any code after it until the sound has finished playing.

    Imports System.Runtime.InteropServices
    
    Public Class Form1
        Private Const SND_SYNC As Integer = &H0
        Private Const SND_ASYNC As Integer = &H1
        Private Const SND_NODEFAULT As Integer = &H2
        Private Const SND_LOOP As Integer = &H8
        Private Const SND_FILENAME As Integer = &H20000
    
        <DllImport("winmm.dll", EntryPoint:="PlaySoundW")>
        Private Shared Function PlaySoundW(<MarshalAs(UnmanagedType.LPWStr)> ByVal pszSound As String, ByVal hmod As IntPtr, ByVal fdwSound As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean
        End Function
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim filename As String = "C:\Test\Sounds\GemPopped.wav"
            PlaySoundW(filename, IntPtr.Zero, SND_FILENAME Or SND_SYNC)
            MessageBox.Show("This message will show after the file is finished playing.")
        End Sub
    End Class
    
     

     I declared a few of the standard flags (Constants) because,  i still don`t know how you want it to operate.  You can read the details for what the flags mean and what they do in the msdn documents for the PlaySound function (link below).

    PlaySound function

     

     If this does not work,  then you either have a corrupted audio file,  maybe the extension has been changed and it is not an actual wave file,  or the audio file was encoded with a codec which you do not have installed on your computer.  I have always installed the K-Lite Mega Codec Pack on all my systems and have never run into a problem playing wave files using any of the methods you say don't work.  


    If you say it can`t be done then i`ll try it

    Sunday, September 24, 2017 11:41 PM
  • Hi.

    thank you for your effort , but it still not working .. the code is working and iam getting the message at the end but i don't hear the file  , it doesn't play 

    i used to use the same code in my previous laptop -which was stolen - with no problems , i used to have ultimate visual studio 2012 and now using the free version of visual studio 2017  . this is the only change that  happened 

    is it possible that the dll file is corrupt or i should reinstall visual studio . i really don't understand what the problem is 

    thank you 

    Saturday, October 7, 2017 5:15 PM
  • hii

    thank you for your effort ..

    what i want is to play many wav files one after the other  ( it play the first till it ends then play the second one and so on )

    when i say it doesn't work , i mean that the code works but i don't hear the file playing .. if you need a certain detail , tell me what it is and i will provide it 

    thanks again

    Saturday, October 7, 2017 5:16 PM
  • what i want is to play many wav files one after the other  ( it play the first till it ends then play the second one and so on )
    Use mciSendString with MM_MCINOTIFY notification to play a new sound when the former has finished.
    Saturday, October 7, 2017 5:48 PM