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


  • 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;


uses BASS, windows, classes;

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


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

procedure TFadeThread.Execute;
var vol,d:single;
 d:=(FEndVolume-FStartVolume)/100/FDuration/0.75; {* see below}
 While not Terminated do begin
   if BASS_ChannelIsActive(FChannel)<>BASS_ACTIVE_PLAYING then Terminate;
   if BASS_ChannelSetAttributes(FChannel,-1,Trunc(vol),-101) then begin
     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 }
     if not Terminated then Sleep(10); { take a nap for 10 ms }
   end else
     Terminate; { channel has been freed before fade was completed }
 { Set the final value }


{*} 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.


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);