File: Sound.pas

package info (click to toggle)
c-evo-dh 3.1-2
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 10,548 kB
  • sloc: pascal: 57,426; xml: 256; makefile: 114; sh: 4
file content (335 lines) | stat: -rw-r--r-- 8,914 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
unit Sound;

interface

uses
  SysUtils, Classes, Graphics, Controls, Forms, Generics.Collections, FileUtil,
  StringTables, Directories, LCLType
  {$IFDEF WINDOWS}, MMSystem, Windows{$ENDIF}
  {$IFDEF UNIX}, Process, AsyncProcess2{$ENDIF};

type
  TPlayStyle = (psAsync, psSync);
  TSoundMode = (smOff, smOn, smOnAlt);

  { TSoundPlayer }

  TSoundPlayer = class(TForm)
  private
    {$IFDEF WINDOWS}
    PrevWndProc: WNDPROC;
    procedure OnMCI(var Msg: TMessage); message MM_MCINOTIFY;
  public
    constructor Create(AOwner: TComponent); override;
    {$ENDIF}
  end;

  { TSound }

  TSound = class
  private
    {$IFDEF UNIX}
    PlayCommand: string;
    SoundPlayerAsyncProcess: TAsyncProcess;
    SoundPlayerSyncProcess: TProcess;
    {$ENDIF}
    function GetNonWindowsPlayCommand: string;
  public
    FDeviceID: Word;
    FFileName: string;
    PlayStyle: TPlayStyle;
    constructor Create(const FileName: string);
    destructor Destroy; override;
    procedure Play(Handle: HWND);
    procedure Stop;
    procedure Reset;
  end;

function PrepareSound(FileName: string): Integer;
procedure PlaySound(FileName: string);
function Play(Item: string; Index: Integer = -1): Boolean;
procedure PreparePlay(Item: string; Index: Integer = -1);

var
  Sounds: TStringTable;
  SoundMode: TSoundMode;
  SoundPlayer: TSoundPlayer;
  SoundList: TObjectList<TSound>;
  PlayingSound: TSound;


implementation

{$R *.lfm}

{$IFDEF UNIX}
resourcestring
  SUnableToPlay = 'PlayStyle=%s: Unable to play %s Message:%s';
  SPlayCommandNotWork = 'The play command %s does not work on your system';
{$ENDIF}

constructor TSound.Create(const FileName: string);
{$IFDEF WINDOWS}
var
  OpenParm: TMCI_Open_Parms;
{$ENDIF}
begin
  PlayStyle := psAsync;
  FFileName := FileName;
  {$IFDEF WINDOWS}
  FDeviceID := 0;
  if FileExists(FFileName) then begin
    OpenParm.dwCallback := 0;
    OpenParm.lpstrDeviceType := 'WaveAudio';
    OpenParm.lpstrElementName := PChar(FFileName);
    mciSendCommand(0, MCI_Open, MCI_WAIT or MCI_OPEN_ELEMENT or
      MCI_OPEN_SHAREABLE, DWORD_PTR(@OpenParm));
    FDeviceID := OpenParm.wDeviceID;
  end
  {$ENDIF}
  {$IFDEF UNIX}
  PlayCommand := GetNonWindowsPlayCommand;
  FDeviceID := 1;
  {$ENDIF}
end;

destructor TSound.Destroy;
begin
  {$IFDEF WINDOWS}
  if FDeviceID <> 0 then
    mciSendCommand(FDeviceID, MCI_CLOSE, MCI_WAIT, 0);
  {$ENDIF}
  {$IFDEF UNIX}
  FreeAndNil(SoundPlayerSyncProcess);
  FreeAndNil(SoundPlayerAsyncProcess);
  {$ENDIF}
  inherited;
end;

function TSound.GetNonWindowsPlayCommand: string;
begin
  Result := '';
  // Try ffplay (ffmpeg)
  if (Result = '') then
    if (FindDefaultExecutablePath('ffplay') <> '') then
      Result := 'ffplay -autoexit -nodisp -loglevel quiet';
  // Try play (sox)
  if (Result = '') then
    if (FindDefaultExecutablePath('play') <> '') then
      Result := 'play -q';
  // Try paplay (pulseaudio-utils)
  if (Result = '') then
    if (FindDefaultExecutablePath('paplay') <> '') then
      Result := 'paplay';
  // Try cvlc (vlc-bin)
  if (Result = '') then
    if (FindDefaultExecutablePath('cvlc') <> '') then
      Result := 'cvlc -q --play-and-exit';
  // Try mpg123
  if (Result = '') then
    if (FindDefaultExecutablePath('mpg123') <> '') then
      Result := 'mpg123 -q';
end;


procedure TSound.Play(Handle: HWND);
{$IFDEF WINDOWS}
var
  PlayParm: TMCI_Play_Parms;
{$ENDIF}
{$IFDEF UNIX}
var
  L: TStringList;
  I: Integer;
{$ENDIF}
begin
  {$IFDEF WINDOWS}
  if FDeviceID <> 0 then
  begin
    PlayParm.dwCallback := Handle;
    mciSendCommand(FDeviceID, MCI_PLAY, MCI_NOTIFY, DWORD_PTR(@PlayParm));
  end
  {$ENDIF}
  {$IFDEF UNIX}
  // How to play in Linux? Use generic Linux commands
  // Use asyncprocess to play sound as SND_ASYNC
  // proceed if we managed to find a valid command
  if PlayCommand <> '' then begin
    L := TStringList.Create;
    try
      L.Delimiter := ' ';
      L.DelimitedText := PlayCommand;
      if PlayStyle = psASync then begin
        if SoundPlayerAsyncProcess = nil then
          SoundPlayerAsyncProcess := TAsyncProcess.Create(nil);
        SoundPlayerAsyncProcess.CurrentDirectory := ExtractFileDir(FFilename);
        SoundPlayerAsyncProcess.Executable := FindDefaultExecutablePath(L[0]);
        SoundPlayerAsyncProcess.Parameters.Clear;
        for I := 1 to L.Count - 1 do
          SoundPlayerAsyncProcess.Parameters.Add(L[I]);
        SoundPlayerAsyncProcess.Parameters.Add(FFilename);
        try
          SoundPlayerAsyncProcess.Execute;
        except
          On E: Exception do
            E.CreateFmt(SUnableToPlay, ['paASync', FFilename, E.Message]);
        end;
        PlayingSound := nil;
      end else begin
        if SoundPlayerSyncProcess = nil then
          SoundPlayerSyncProcess := TProcess.Create(nil);
        SoundPlayerSyncProcess.CurrentDirectory := ExtractFileDir(FFilename);
        SoundPlayerSyncProcess.Executable := FindDefaultExecutablePath(L[0]);
        SoundPlayersyncProcess.Parameters.Clear;
        for I := 1 to L.Count - 1 do
          SoundPlayerSyncProcess.Parameters.Add(L[I]);
        SoundPlayerSyncProcess.Parameters.Add(FFilename);
        try
          SoundPlayerSyncProcess.Execute;
          SoundPlayersyncProcess.WaitOnExit;
        except
          On E: Exception do
            E.CreateFmt(SUnableToPlay, ['paSync', FFilename, E.Message]);
        end;
        PlayingSound := nil;
      end;
    finally
      FreeAndNil(L);
    end;
  end
  else
    raise Exception.CreateFmt(SPlayCommandNotWork, [PlayCommand]);
  {$ENDIF}
end;

procedure TSound.Stop;
begin
  {$IFDEF WINDOWS}
  mciSendCommand(FDeviceID, MCI_STOP, 0, 0);
  {$ENDIF}
  {$IFDEF UNIX}
  if SoundPlayerSyncProcess <> nil then SoundPlayerSyncProcess.Terminate(1);
  if SoundPlayerAsyncProcess <> nil then SoundPlayerAsyncProcess.Terminate(1);
  {$ENDIF}
end;

procedure TSound.Reset;
begin
  {$IFDEF WINDOWS}
  mciSendCommand(FDeviceID, MCI_SEEK, MCI_SEEK_TO_START, 0);
  {$ENDIF}
end;

{$IFDEF WINDOWS}
function WndCallback(Ahwnd: HWND; uMsg: UINT; wParam: WParam; lParam: LParam):LRESULT; stdcall;
var
  Message: TMessage;
begin
  if (uMsg = MM_MCINOTIFY) then begin
    Message.msg := uMsg;
    Message.wParam := wParam;
    Message.lParam := lParam;
    SoundPlayer.OnMCI(Message);
  end;
  Result := CallWindowProc(SoundPlayer.PrevWndProc, Ahwnd, uMsg, WParam, LParam);
end;

procedure TSoundPlayer.OnMCI(var Msg: TMessage);
begin
  if (Msg.wParam = MCI_NOTIFY_SUCCESSFUL) and (PlayingSound <> nil) then
  begin
    PlayingSound.Reset;
    PlayingSound := nil;
  end;
end;

constructor TSoundPlayer.Create(AOwner: TComponent);
begin
  inherited;
  // MM_MCINOTIFY is not handled by LCL, fallback to low lever handling
  // https://wiki.lazarus.freepascal.org/Win32/64_Interface#Processing_non-user_messages_in_your_window
  PrevWndProc := Windows.WNDPROC(SetWindowLongPtr(Self.Handle, GWL_WNDPROC, PtrInt(@WndCallback)));
end;
{$ENDIF}

function PrepareSound(FileName: string): Integer;
begin
  Result := 0;
  while (Result < SoundList.Count) and (SoundList[result].FFileName <> FileName) do
    Inc(Result);
  if Result = SoundList.Count then begin
    // First time this sound is played
    SoundList.Add(TSound.Create(FileName));
    Result := SoundList.Count - 1;
  end;
end;

procedure PlaySound(FileName: string);
begin
  if PlayingSound <> nil then Exit;
  if SoundPlayer = nil then
    Application.CreateForm(TSoundPlayer, SoundPlayer);
  PlayingSound := SoundList[PrepareSound(FileName)];
  if PlayingSound.FDeviceID = 0 then
    PlayingSound := nil
  else
    PlayingSound.Play(SoundPlayer.Handle);
end;

function Play(Item: string; Index: Integer = -1): Boolean;
var
  WavFileName: string;
begin
  Result := False;
  if (Sounds = nil) or (SoundMode = smOff) or (Item = '') then
  begin
    Result := True;
    Exit;
  end;
  WavFileName := Sounds.Lookup(Item, Index);
  Assert(WavFileName[1] <> '[');
  Result := (WavFileName <> '') and (WavFileName[1] <> '[') and (WavFileName <> '*');
  if Result then
    // SndPlaySound(pchar(GetSoundsDir + DirectorySeparator + WavFileName + '.wav'), SND_ASYNC)
    PlaySound(GetSoundsDir + DirectorySeparator + WavFileName);
end;

procedure PreparePlay(Item: string; Index: Integer = -1);
var
  WavFileName: string;
begin
  if (Sounds = nil) or (SoundMode = smOff) or (Item = '') then
    Exit;
  WavFileName := Sounds.Lookup(Item, Index);
  Assert(WavFileName[1] <> '[');
  if (WavFileName <> '') and (WavFileName[1] <> '[') and (WavFileName <> '*') then
    PrepareSound(GetSoundsDir + DirectorySeparator + WavFileName);
end;

procedure UnitInit;
begin
  SoundList := TObjectList<TSound>.Create;
  PlayingSound := nil;
  SoundPlayer := nil;
end;

procedure UnitDone;
begin
  if PlayingSound <> nil then begin
    PlayingSound.Stop;
    Sleep(222);
  end;
  FreeAndNil(SoundList);
  if Sounds <> nil then
    FreeAndNil(Sounds);
end;

initialization

UnitInit;

finalization

UnitDone;

end.