Author Topic: DELPHI CODE: Threaded Fade unit  (Read 3756 times)

Zep

  • Posts: 27
DELPHI CODE: Threaded Fade unit
« on: 18 Sep '02 - 20:50 »
People needed multithreaded fade in/out Delphi code. Here you have ... (hopefully it works ok)  ;)

Code: [Select]
unit BassFadeThread;

interface

uses BASS, windows, classes;

type
 TFadeThread = class(TThread)
 private
   FChannel: DWORD;
   FStartVolume: integer;
   FEndVolume: integer;
   FDuration: single;
 protected
   procedure Execute; override;
 public
   constructor Create(channel:DWORD; StartVolume, EndVolume:integer; Duration:Single);
 end;

implementation


constructor TFadeThread.Create(channel:DWORD; StartVolume, EndVolume:integer; Duration:Single);
begin
 inherited Create(true); { Create thread as suspended }
 FreeOnTerminate:=true;  { Fire and forget }
 Priority:=tpHighest;    { Bump up the priority for smoother fade's }
 FChannel:=channel;
 FStartVolume:=StartVolume;
 FEndVolume:=EndVolume;
 FDuration:=Duration;
 Resume; { Start the thread }
end;


procedure TFadeThread.Execute;
var vol,d:single;
begin
 d:=(FEndVolume-FStartVolume)/100/FDuration/0.75; {* see below}
 vol:=FStartVolume;
 While not Terminated do begin
   if BASS_ChannelIsActive(FChannel)<>BASS_ACTIVE_PLAYING then Terminate;
   if BASS_ChannelSetAttributes(FChannel,-1,Trunc(vol),-101) then begin
     vol:=vol+d;
     if d>0 then begin { Fade-in  }
       if Trunc(vol)>=FEndVolume then Terminate; { volume has reached it's highes value }
     end else begin    { Fade-out }
       if Trunc(vol)<=FEndVolume then Terminate; { volume has reached it's lowest value }
     end;
     if not Terminated then Sleep(10); { take a nap for 10 ms }
   end else
     Terminate; { channel has been freed before fade was completed }
 end;
 { Set the final value }
 BASS_ChannelSetAttributes(FChannel,-1,FEndVolume,-101);
end;

end.



{*} I don't know why I have to use value 0.75 there, but that value was necessary to make the duration ok.
Please could somebody tell me why?
This fade-thread is heavily stripped down copy of my own fade-thread and I haven't tested if it's working 100%. I only copied the main portions of my thread into this message. Try to correct any errors and post the working code here (If there are errors). Please post also enhancements if you like.

USAGE:

var MyFade:TFadeThread;
MyFade:=TFadeThread.create(channel, startvolume, endvolume, duration);



You can save the "MyFade" value if you need it for something, but you can also forget the value and go on with your own code because the thread object does terminating and freeing itself. Just FIRE-AND-FORGET.

volumes are 0..100 (integer)
duration is in seconds (single)



example: (2.5 seconds fade-out)
MyFade:=TFadeThread.create(my_channel, 100, 0, 2.5);

example: (0.3 seconds fade-in to volume value 75
MyFade:=TFadeThread.create(my_channel, 0, 75, 0.3);