{ SDL sound routines }
{ Based on units of JEDI-SDL project }
{ Copyright (c)2004-2100, JEDI-SDL Team }
{ Unit sound.pas created by Lucas Alexandre }

unit sound;

interface

uses Console, SDL, SDL_Mixer, windows;

function play(filename: String; loops: integer): integer;
procedure FreeMem;
procedure EndCH(channel: integer); cdecl; forward;
implementation
uses rfile, rgame, sysUtils;
const
NUMCHANNELS=50;

function play(filename: String; loops: integer): integer;
var snd: pMix_chunk;
channel: integer;
begin
if filename='' then exit;
randomize;
snd:=Mix_LoadWav(pchar(filename));
channel:=random(NUMCHANNELS);
while (Mix_playing(channel))=1 do channel:=random(NUMCHANNELS);
Mix_PlayChannel(channel,snd,loops);
if (Mix_Playing(channel)=0) then Mix_PlayChannel(channel,snd,loops);
play:=channel;
while Mix_Playing(channel)<>0 do
begin
if keypressed then
if upcase(readkey)='F' then
begin
mix_HaltChannel(channel);
exit;
end;
sleep(1);
end;
if not fileExists(filename) then
MessageBox(GetConsoleWindow,pchar(filename),pchar(game.title),0);
FreeMem;
end;

{ Deallocate old chunks when channel finishes }

procedure EndCH(channel: integer); cdecl; { This procedure is passed as a pointer for Mix_ChannelFinished }
begin
Mix_FreeChunk(Mix_GetChunk(channel));
end;

{ Check and deallocate old chunks from memory }

procedure FreeMem;
var i: integer;
begin
for i:=0 to NUMCHANNELS do
if Mix_Playing(i)=0 then
Mix_ChannelFinished(@EndCH);
end;

begin
if (Mix_OpenAudio(44100,AUDIO_S16,2,4096))<0 then halt;
Mix_AllocateChannels(NUMCHANNELS);
end.
