Click here to Skip to main content
Email Password   helpLost your password?

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.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralRecording coinciding visualizing?
fmmahdi
8:40 2 Feb '10  
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.
dnair926
10:12 21 Aug '09  
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!
jharris4
12:43 9 Jul '09  
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 sound
selassie747
2:18 8 Jul '09  
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 .
Questionplaying wave files in vb.net
selassie747
2:01 3 Jul '09  
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?
Claudio Nicora
6:58 26 May '09  
Great article and explanation. Thumbs Up

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?
Angelo Cresta
11:33 26 May '09  
It use the standard output, I don't know it is possible the choose a specific device.
Regards /// Angelo
GeneralHow to stop the sound
chaisutek
12:10 8 Jun '08  
I have a question.
How to stop the sound?
Thanks...
Questionduration wave file vb.net
Member 4283494
8:28 22 May '08  
how do i get the duration of .wav file in vb.net???Confused
AnswerRe: duration wave file vb.net
Code_Doctor
22:37 22 May '08  
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.NET
bijivn
2:38 22 Apr '08  
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.
Generalthanks
x-files
13:22 4 Dec '07  
good demo , thanks Rose
Generalloop sound
I Hate My Computer
19:21 27 May '07  
can I loop the sound with this code? If so how?



Thanks for the code
GeneralVery Good
merdynn
7:34 11 Apr '07  
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 Good
Angelo Cresta
21:50 12 Apr '07  
Thank you!

Angel
GeneralCool
rexha
23:37 18 Jul '06  
:-OI would like to know if there is a possibility to paly mp3. or wma file?
Does anybody can help me?
AnswerRe: Cool
98z28
13:28 15 Sep '06  
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 time
Parth Bhatt
8:37 22 Jun '06  
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
GeneralProblem playing .wmv files
seva04121973
2:51 22 Jun '06  
in code

AxMediaPlayer1.FileName="c:\temp\test.avi"

AxMediaPlayer1.Play

working properly, but when I try to play .wmv

files

AxMediaPlayer1.FileName="c:\temp\test.wmv"

AxMediaPlayer1.Play

i got error in line axmediaplayer1.play

files test.avi and test.wmv exist adn they work properly in any player

Why?

I think that this error is same one as if I dont have file or file is wrong.

"An unhandled exeption of type

System.runtime.interoptservices.COMExeption

occured in axiteropt.mediaplayer.dll

Additional information: Unspecified error"



File test.wmv exist and work in Windows media player when i start his directly

Thanks in advance
GeneralRe: time frame in AxWindowsMediaPlayer
seva04121973
2:49 22 Jun '06  
Try this:
AxMediaPlayer1.position= 'number of frame'
AxMediaplayer1.play

GeneralJust to Play a WAV File?
WD9DAN
3:24 19 Jun '06  
I understand that the API presented here may offer some additional functionality. But, since folks are wanting to know how to PLAY a *.Wav file in VB.NET, what's wrong with the following code snippet?

My.Computer.Audio.Play("ringingout.wav", AudioPlayMode.Background)

Would that not be the .NET way to do it?

I hope this helps others, that simply want to play a sound.

DBDoctor - Dan.
GeneralRe: Just to Play a WAV File?
98z28
13:17 15 Sep '06  
That feature was added to 2.0 version of the .NET Framework.

DotNetFramework 1.0/1.1 does NOT have those capabilities. Only version 2.0 has it.


Jason

GeneralAny suggestion on how to record wav / mp3 files ?
Parik Advani
3:58 12 Jun '06  
My application has a module in which we want to be able to give the user an option to add a voice tag to their module. Any idea what classes I could use to do that ? I tried a bunch of the stuff available online but nothing really worked ?

-Parik.
http://parik.in

AnswerRe: Any suggestion on how to record wav / mp3 files ?
98z28
13:05 15 Sep '06  
Hi, one of the easier ways to record is to use the MCI Command Interface. It is 'somewhat' flexible and gives you the ability to specify some of the quality settings.

I have a full tutorial on how to Learn to program the mciSendString Command Interface in your applications to be able to perform most media based functionality.

My site link is in my signature at the bottom of this post.

I do plan on releasing a new version of my csMusicLibrary Library for Visual Basic 2005 in the near future. It will have basic recording capabilities already incorporated in the library. The class is almost complete, but I have to finish debugging plus some tweaking here and there.

But you may not want to wait until the new library is released. So I suggest you go check out the tutorial I made.

Hope this helps Smile


Jason




GeneralIt's not working for me
RandomSkratch
20:27 5 Apr '06  
I'm pretty new to VB (started in Jan) but I would really like to add this to one of my projects. I copied and pasted the code but I keep getting

PlayWaveFile is not a member of MAD.Sound (MAD is the title of the project)

What am I doing wrong?



Last Updated 16 Feb 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010