unit Sounds;

interface

uses Windows, mmSystem, Classes, Forms, WavePlay, SharedData;

var
  SoundsEnabled : Boolean;

const
  numwaves = 16;

var
  waves : array[1..numwaves] of TWave;

procedure Initialize;
procedure Finalize;
procedure Sound(var Snd : TWave);
function  PlayDone:Boolean;
procedure ChooseAmbSound;
procedure ClosePlayer;

implementation

{$RESOURCE 'Media\Sounds\Waves.Res'}

var
  wPlayer : TWavePlayer;
  NoHardware : Boolean;

function PlayDone:Boolean;
begin
  if((NoHardware)or(not SoundsEnabled)or(wPlayer.GetProgress1000>=1000)) then
    Result:=True
  else
    Result:=False;
end;

procedure Sound(var Snd : TWave);
begin
  if((not NoHardware) and SoundsEnabled and (not Snd.LastError)) then
  begin
    wPlayer.Open(@Snd);
    if(not wPlayer.LastError) then
    begin
      wPlayer.Prepare(@Snd);
      if(not wPlayer.LastError) then
        wPlayer.Play();
    end;
  end;
end;

function FindWave:Boolean;
begin
  if(waveOutGetNumDevs=0) then
    Result:=False
  else
    Result:=True;
  NoHardware:=not Result;
end;

procedure Initialize;
var
  i : integer;
begin
  NoHardware := not FindWave;
  if(NoHardware) then
    exit;
  for i := 1 to numwaves do
  begin
    waves[i]:=TWave.Create;
    waves[i].Load(MAKEINTRESOURCE(5000+i));
  end;
  wPlayer:=TWavePlayer.Create;
  SoundsEnabled:=True;
end;

procedure Finalize;
var
  i : integer;
begin
  if(NoHardware) then exit;
  for i := 1 to numwaves do
    waves[i].Destroy;
  wPlayer.Destroy;
end;

// Эта функция вызывается один раз в секунду. Средний перерыв между
// звуками - около 10 секунд.

procedure ChooseAmbSound;
begin
  if PlayDone and (Random(2) = 1) then
    Sound(waves[numwaves-Random(numwaves)]);
end;

procedure ClosePlayer;
begin
  if((not NoHardware)and(SoundsEnabled)) then
    wPlayer.Close;
end;

end.
