Click here to Skip to main content
Click here to Skip to main content

Play Waves in VB.NET

By , 16 Feb 2005
 

Sample Image

Introduction

This is a simple class that shows how to play Wave files in a .NET project, using Windows API. Here, you will find the way to play embedded resources, external files, or Windows system Waves.

Using the code

Using the code is very simple, you have to choose if you want to play a file: Sound.PlayWaveFile("Filename.wav"), an embedded resource: Sound.PlayWaveResource("Embedded.wav"), or a system sound: Sound.PlayWaveSystem("SystemExit").

    ...
Public Class Sound
    Declare Auto Function PlaySound Lib "winmm.dll" (ByVal name _
      As String, ByVal hmod As Integer, ByVal flags As Integer) As Integer

    Declare Auto Function PlaySound Lib "winmm.dll" (ByVal name _
      As Byte(), ByVal hmod As Integer, ByVal flags As Integer) As Integer

    Public Const SND_SYNC = &H0 ' play synchronously 
    Public Const SND_ASYNC = &H1 ' play asynchronously 
    Public Const SND_MEMORY = &H4  'Play wav in memory
    Public Const SND_ALIAS = &H10000 'Play system alias wav 
    Public Const SND_NODEFAULT = &H2
    Public Const SND_FILENAME = &H20000 ' name is file name 
    Public Const SND_RESOURCE = &H40004 ' name is resource name or atom 
    ...
End Class

'Using the code:

    Private Sub btnFile_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnFile.Click
        'File Located in executable dir, change it if you need
        Sound.PlayWaveFile("sn01088a.wav")
    End Sub

    Private Sub btnEmbed_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnEmbed.Click
        'Remeber to include the wave in the project 
        'and then in the "build action"
        'properties set it as: "Embedded Resource"
        Sound.PlayWaveResource("The Microsoft Sound.wav")
    End Sub

    Private Sub btnSystem_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnSystem.Click

        'Here some ...

        '"SystemQuestion"
        '"SystemExclaimation"
        '"SystemHand"
        '"Maximize"
        '"MenuCommand"
        '"MenuPopup"
        '"Minimize"
        '"MailBeep"
        '"Open"
        '"Close"
        '"SystemAsterisk"
        '"RestoreUp"
        '"RestoreDown"
        '"SystemExit"
        '"SystemStart"

        Sound.PlayWaveSystem("SystemExit")
    End Sub

All the job is done by the PlaySound function.

Points of Interest

This is an "all in one" Sound class for your .NET applications (File, Resource, System sounds).

History

First release.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Angelo Cresta
Chief Technology Officer
Switzerland Switzerland
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionunusable codememberchriscore31 Jul '12 - 5:08 
useless code
AnswerRe: unusable codememberAngelo Cresta1 Aug '12 - 21:05 
not in Feb 2005.
GeneralVB class for Sound PlayermemberMember 836841315 Nov '11 - 6:25 
Excellent class. Solved my problem. Thank you.
QuestionCan't get it to workmemberxgonzalez8114 May '11 - 11:34 
The class works fine on the local host but does not work at all once it's up on the actual server. What can I do to fix this?
GeneralGreat Class Thank youmemberCDPerez21 Sep '10 - 6:01 
Thank you I was looking for a way to Notify my users for events due that during entry time, sometimes they do not look at the screen and keep typing.
GeneralGreat workmemberJohnAndre25 Aug '10 - 5:42 
Merci!
GeneralMy vote of 5memberJohnAndre25 Aug '10 - 5:41 
Great work!
QuestionRecording coinciding visualizing?memberfmmahdi2 Feb '10 - 7:40 
Thanks for your simple powerful source, is this possible to record simultaneously visualizing? I mean is this any possibility to get a specific samples in a period?
QuestionDoesn't work on web server but works on development machine.memberdnair92621 Aug '09 - 9:12 
I downloaded the code and added to my project. Sound works on development machine but not when deployed to web server. I am trying to play the system's exclamation sound.("SystemExclamation")
GeneralFantastic!memberjharris49 Jul '09 - 11:43 
I was looking for a freeware app to download, heck with this I was able to right my own to do just what I need. good job.
 
JHarris

QuestionCalling a method to execute soundmemberselassie7478 Jul '09 - 1:18 
I tried out a code to play files stored in the resource folder. It is working alright, I wrote these codes to play these files in a Sub method for it to be executed when called. However its more than one method be called within the event of when a button is clicked.
 
What is happening is that, when the event takes place, that is when the button is clicked, only one method is executed.
 

--------------------------------------------------------------------
 

These are examples of the codes:
I've got two different Subs I'll be calling in an event, both are to play sound files. Word() and Say()
 

Public Sub Word()
.
.
.
 
If My.Resources.mention.CanRead Then
Dim bStr(My.Resources.mention.Length) As Byte
My.Resources.mention.Read(bStr, 0, My.Resources.mention.Length)
My.Computer.Audio.Play(bStr, AudioPlayMode.Background)
End If
 
End Sub
 
Public Sub Say()
.
.
.
 
If My.Resources.pronounce.CanRead Then
Dim bStr(My.Resources.pronounce.Length) As Byte
My.Resources.pronounce.Read(bStr, 0, My.Resources.pronounce.Length)
My.Computer.Audio.Play(bStr, AudioPlayMode.Background)
End If
 
End Sub
 

Below is the event which is when the button 'btnStart' is clicked.
 
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles btnStart.Click
Say()
Word()
 

End Sub
 
When I execute this and click the 'btnStart' button the method that is executed is the second i.e. Word() only.
 
I can't understand why, what I want it to do is execute Say() then execute Word().
 

Is there a way to do this or is it that two methods can't be called within an event, can I get any help for this?????
 
I am really desperate here Confused | :confused: .
Questionplaying wave files in vb.netmemberselassie7473 Jul '09 - 1:01 
hello,
 
I'm trying to find out how to play wave files stored in a connected access database.
 
How can I do this please?
 

I tried the code I found from this link:
http://www.aboutmydot.net/index.php/play-wav-file-in-vbnet
 
-----------------------------------------------------------------------
 
Dim Sound As New System.Media.SoundPlayer()
 
Sound.SoundLocation = "your path to the .wav file" 'ex.: c:\mysound.wav
Sound.Load()
Sound.Play()
 
-----------------------------------------------------------------------
 

It was ok, but I don't want the path to the .wav file to necessarily start from c:\ since I'm hoping to have this project used on a different machine, meaning if I link it to specific path it would not play on a different machine.
 
So instead of something like:
"C:\Documents and Settings\User\My Documents\Project\Sounds\mysound.wav"
 
as the link to the file, in the database field(eg.sWord)I made it short to be like:
 
\Sounds\mysound.wav
 
since the access file would also be in the folder Project, so that it could easily locate the wav file.
 
Therefore within the code instead of
 
Sound.SoundLocation = "your path to the .wav file" 'ex.: c:\mysound.wav
 
I made it
 
Sound.SoundLocation = SWordTextbox.Text where SWord.Textbox is the field in the database having the link to the wav file and therefore it's text property assigns the link to the attribute .SoundLocation.
 

I hope I've explained better, I'm kind of new to VB.net. Any help will be greatly appreciated.
 
Thanks.
QuestionIs there a way to change output device?memberClaudio Nicora26 May '09 - 5:58 
Great article and explanation. Thumbs Up | :thumbsup:
 
Do you know a way to select the device to use for audio playing (other than changing the default device in control panel)?
 
Thanks
Claudio
 

Visit my website for some interesting .NET free tools: http://coolsoft.altervista.org

AnswerRe: Is there a way to change output device?memberAngelo Cresta26 May '09 - 10:33 
It use the standard output, I don't know it is possible the choose a specific device.
Regards /// Angelo
QuestionHow to stop the soundmemberchaisutek8 Jun '08 - 11:10 
I have a question.
How to stop the sound?
Thanks...
Questionduration wave file vb.netmemberMember 428349422 May '08 - 7:28 
how do i get the duration of .wav file in vb.net???Confused | :confused:
AnswerRe: duration wave file vb.netmemberCode_Doctor22 May '08 - 21:37 
You'll have to extend the code yourself.
 
This can be done by using the same API winmm.dll that is being used.
Simply add some more declarations, and work out some additional methods.
 
Here are just a few, I'll suggest you research the API at msdn.microsoft.com

 

    Private Declare Function waveOutOpen Lib "winmm.dll" Alias "waveOutOpen" (ByVal lphWaveOut As Long, ByVal uDeviceID As Long, ByVal lpFormat As WAVEFORMATEX, ByVal dwCallback As Long, ByVal dwInstance As Long, ByVal dwFlags As Long) As Long
    Private Declare Function waveOutWrite Lib "winmm.dll" Alias "waveOutWrite" (ByVal hWaveOut As Long, ByVal lpWaveOutHdr As WAVEHDR, ByVal uSize As Long) As Long
    Private Declare Function waveOutPause Lib "winmm.dll" Alias "waveOutPause" (ByVal hWaveOut As Long) As Long
    Private Declare Function waveOutRestart Lib "winmm.dll" Alias "waveOutRestart" (ByVal hWaveOut As Long) As Long
    Private Declare Function waveOutSetPitch Lib "winmm.dll" Alias "waveOutSetPitch" (ByVal hWaveOut As Long, ByVal dwPitch As Long) As Long
    Private Declare Function waveOutGetPosition Lib "winmm.dll" Alias "waveOutGetPosition" (ByVal hWaveOut As Long, ByVal lpInfo As MMTIME, ByVal uSize As Long) As Long
 
    ' Management of errors.
    Private Declare Function waveOutGetErrorText Lib "winmm.dll" Alias "waveInGetErrorTextA" (ByVal err As Long, ByVal lpText As String, ByVal uSize As Long) As Long
 
    Private Declare Function waveOutClose Lib "winmm.dll" Alias "waveOutClose" (ByVal hWaveOut As Long) As Long
    Private Declare Function waveOutGetID Lib "winmm.dll" Alias "waveOutGetID" (ByVal hWaveOut As Long, ByVal lpuDeviceID As Long) As Long
    Private Declare Function waveOutGetNumDevs Lib "winmm.dll" Alias "waveOutGetNumDevs" () As Long
    Private Declare Function waveOutPrepareHeader Lib "winmm.dll" Alias "waveOutPrepareHeader" (ByVal hWaveOut As Long, ByVal lpWaveOutHdr As WAVEHDR, ByVal uSize As Long) As Long
    Private Declare Function waveOutUnprepareHeader Lib "winmm.dll" Alias "waveOutUnprepareHeader" (ByVal hWaveOut As Long, ByVal lpWaveOutHdr As WAVEHDR, ByVal uSize As Long) As Long
 

    Public Const WAVE_MAPPER = -1&
    Public Const WAVE_FORMAT_PCM = 1
 
    Public Structure WAVEHDR
        Dim lpData As Int32
        Dim dwBufferLength As Int32
        Dim dwBytesRecorded As Int32
        Dim dwUser As Int32
        Dim dwFlags As Int32
        Dim dwLoops As Int32
        Dim reserved As Int32
        Dim lpNext As Int32
    End Structure
 
    Public Structure WAVEFORMATEX
        Dim wFormatTag As Int16
        Dim nChannels As Int16
        Dim nSamplesPerSec As Int32
        Dim nAvgBytesPerSec As Int32
        Dim nBlockAlign As Int16
        Dim wBitsPerSample As Int16
        Dim cbSize As Int16
    End Structure
 
    Structure MMTIME
        Dim wType As Long
        Dim u As Long
    End Structure
 

 
That should be enough to get ya started. It's a pretty easy API to get, have fun. Hope this helps.
QuestionDisplay of imgae files and .avi and .swf in VB.NETmemberbijivn22 Apr '08 - 1:38 
I would like to is there any way I can run the above mentioned files using a contol in VB.NET. This is for the purpose of displaying advertisement that comes in these mentioned format.
Generalthanksmemberx-files4 Dec '07 - 12:22 
good demo , thanks Rose | [Rose]
Generalloop soundmemberI Hate My Computer27 May '07 - 18:21 
can I loop the sound with this code? If so how?
 

 
Thanks for the code
GeneralVery Goodmembermerdynn11 Apr '07 - 6:34 
This class file is extremely efficient...I found this useful for a product to play a sound on a notification....Exactly what I was looking for....something to play a sound...any sound....something that has a small foot-print and add next to nothing on the memory footprint.
 
Micronic
GeneralRe: Very GoodmemberAngelo Cresta12 Apr '07 - 20:50 
Thank you!
 
Angel
GeneralCoolmemberrexha18 Jul '06 - 22:37 
:-OI would like to know if there is a possibility to paly mp3. or wma file?
Does anybody can help me?
AnswerRe: Coolmember98z2815 Sep '06 - 12:28 
Yes, there are a few ways you can play mp3/wma files.
 
You can use a 3rd party library. Example: the Bass Sound System or FMod.
 
You can use the Windows Media Player Component.
 
Or the method I recommend, is to use the MCI Command Interface, which is supported on Win9x all the way up to the latest Windows XP versions and such. You do not have to really worry about compatibility or worry about Distributing any files with your applications going this route.
 
I have pre-made librarys that will do what you want and more, and is ready to go. Or you can check out the tutorial at my website that will show you how to use the mciSendString Command Interface yourself to make a full-featured media application.
 
It is completely up to you. Hope this helps Smile | :)
 

 
Jason
 
GeneralHelp for AxWindiwsMediaPlayer with timememberParth Bhatt22 Jun '06 - 7:37 
Hi,
I m using .net 2003. I don’t fine anything like .position with control AxWindowsMediaPlayer. I want to stop playing file at specific time too. I mean one can enter starting and terminating time through edit box and control must repetitively play file in between that time only.
If any one has a solution without .position then kindly post the same.
Regards,
-Parth
 

-- modified at 13:37 Thursday 22nd June, 2006

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 16 Feb 2005
Article Copyright 2005 by Angelo Cresta
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid