Author: Tomas Rutkauskas
Four different ways to load and play sound files
Answer:
There are four ways of loading and playing sound in your program:
Use the sndPlaySound() function to directly play a wave file
Read the wave file into memory, then use the sndPlaySound() to play the wave file
Use sndPlaySound to directly play a wave file thats embedded in a resource file
attached to your application.
Read a wave file thats embedded in a resource file attached to your application
into memory, then use the sndPlaySound() to play the wave file
Sample Code:
1 unit PlaySnd1;
2
3 interface
4
5 uses
6 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
7 StdCtrls;
8
9 type
10 TForm1 = class(TForm)
11 PlaySndFromFile: TButton;
12 PlaySndFromMemory: TButton;
13 PlaySndbyLoadRes: TButton;
14 PlaySndFromRes: TButton;
15 procedure PlaySndFromFileClick(Sender: TObject);
16 procedure PlaySndFromMemoryClick(Sender: TObject);
17 procedure PlaySndFromResClick(Sender: TObject);
18 procedure PlaySndbyLoadResClick(Sender: TObject);
19 private
20 { Private declarations }
21 public
22 { Public declarations }
23 end;
24
25 var
26 Form1: TForm1;
27
28 implementation
29
30 {$R *.DFM}
31 {$R snddata.res} // Resource file containing the *.wav file
32
33 uses
34 MMSystem;
35
36 {1. Use the sndPlaySound() function to directly play a wave file}
37
38 procedure TForm1.PlaySndFromFileClick(Sender: TObject);
39 begin
40 sndPlaySound('hello.wav', SND_FILENAME or SND_SYNC);
41 end;
42
43 {2. Read the wave file into memory, then use the sndPlaySound() to play the wave
44 file}
45
46 procedure TForm1.PlaySndFromMemoryClick(Sender: TObject);
47 var
48 f: file;
49 p: pointer;
50 fs: integer;
51 begin
52 AssignFile(f, 'hello.wav');
53 Reset(f, 1);
54 fs := FileSize(f);
55 GetMem(p, fs);
56 BlockRead(f, p^, fs);
57 CloseFile(f);
58 sndPlaySound(p, SND_MEMORY or SND_SYNC);
59 FreeMem(p, fs);
60 end;
61
62 {3. Use sndPlaySound to directly play a wave file thats embedded in a resource file
63 attached
64 to your application}
65
66 procedure TForm1.PlaySndFromResClick(Sender: TObject);
67 begin
68 PlaySound('HELLO', hInstance, SND_RESOURCE or SND_SYNC);
69 end;
70
71 {4. Read a wave file thats embedded in a resource file attached to your application
72 into memory,
73 then use the sndPlaySound() to play the wave file}
74
75 procedure TForm1.PlaySndbyLoadResClick(Sender: TObject);
76 var
77 h: THandle;
78 p: pointer;
79 begin
80 h := FindResource(hInstance, 'HELLO', 'WAVE');
81 h := LoadResource(hInstance, h);
82 p := LockResource(h);
83 sndPlaySound(p, SND_MEMORY or SND_SYNC);
84 UnLockResource(h);
85 FreeResource(h);
86 end;
87
88 end.
|