Playing a custom sound
Copyright © 2000 Ernesto De Spirito
![]() |
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:
uses MMSystem;
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:
uses MMSystem;
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.
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:
uses MMSystem;
{$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:
uses Windows, MMSystem;
{$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.
![]() |



