Mega Code Archive

 
Categories / Delphi / Multimedia
 

Playing a custom sound

Title: Playing a custom sound Question: How can I play a WAV file? I need some alternatives... Answer: If you want to play the basic system sounds, call MessageBeep with the appropriate parameter. Call MessageBeep(-1); if you want to make the speaker beep. To play a WAV sound, you can use a TMediaPlayer object, but if you want something fast, the easiest way is calling the API function sndPlaySound (declared in the mmsystem unit). For example: procedure TForm1.Button1Click(Sender: TObject); begin sndPlaySound('C:\Windows\Media\Tada.wav', SND_NODEFAULT Or SND_ASYNC Or SND_LOOP); end; procedure TForm1.Button2Click(Sender: TObject); begin sndPlaySound(nil, 0); // Stops the sound end; If you intend to play a sound more or less often, maybe you should consider loading the file in memory and playing it from there: var tada: string; procedure TForm1.Button1Click(Sender: TObject); begin sndPlaySound(Pointer(tada), SND_MEMORY Or SND_NODEFAULT Or SND_ASYNC); end; initialization tada := LoadFile('C:\Windows\Media\Tada.wav'); finalization tada := ''; // Releases the memory taken by the string end. NOTE: LoadFile has been featured in the article "Reading a file into a string" (keyword: LoadFile). You can embed one or more wave files in your executable and play them from there. First, you need to create a resource (.RES) file. To do this, create a .RC file, for example named sounds.rc: tada wave c:\windows\media\tada.wav chimes wave c:\windows\media\chimes.wav Then you need to compile it with the resource compiler (BRCC32.EXE in Delphi\Bin directory) and you will have a file named sounds.res that you can load in your project with the $R directive. To play the sound directly from the executable call PlaySound (instead of sndPlaySound) with the SND_RESOURCE flag: {$R sounds.res} procedure TForm1.Button1Click(Sender: TObject); begin PlaySound('chimes', hInstance, SND_RESOURCE or SND_SYNC); PlaySound('tada', hInstance, SND_RESOURCE or SND_ASYNC); end; Again, if you are going to play a sound more or less often, you should consider loading the resource in memory and playing it from there: {$R sounds.res} var tada: Pointer; procedure TForm1.Button1Click(Sender: TObject); begin sndPlaySound(tada, SND_MEMORY or SND_NODEFAULT or SND_ASYNC); end; initialization // Here we use some castings to avoid using another variable tada := Pointer(FindResource(hInstance, 'tada', 'wave')); if tada nil then begin tada := Pointer(LoadResource(hInstance, HRSRC(tada))); if tada nil then tada := LockResource(HGLOBAL(tada)); end; end.