unit uSoundManager;

interface

uses classes, ShellAPI, bass_simple, windows, System.SysUtils;

type
  TSongMachine = class(TObject)

  private

  public
    constructor Create;
    destructor Destroy;
    procedure PlayPublic(AFileName: string; aVolume: string);
    procedure PlaySilent(AFileName: string; aVolume: string);

  end;

implementation

uses uGeneral;

var
  mp: TBassSimple;

  { SongMachine }

constructor TSongMachine.Create;
begin
  mp := TBassSimple.Create(0);
end;

destructor TSongMachine.Destroy;
begin
  mp.FreeStream;
  mp.Free;
end;

function TimeToSeconds(const timeStr: string): Integer;
var
  minutes, seconds: Integer;
begin
  if TryStrToInt(Copy(timeStr, 1, 2), minutes) and
    TryStrToInt(Copy(timeStr, 4, 5), seconds) then
  begin
    result := minutes * 60 + seconds;
  end
  else
  begin
    result := -1;
  end;
end;

procedure TSongMachine.PlaySilent(AFileName: string; aVolume: string);
var
  sec: string;
  mm: TBassSimple;
begin
  try
    if not FileExists(AFileName) then
    begin
      TTW_Bot.toLog( 'TSongMachine', 'PlayPublic', 'Нет файла ' + AFileName,2);
      exit;
    end;
    mm := TBassSimple.Create(0);
    try
      mm.OpenFile(AFileName);
      sec := inttostr(TimeToSeconds(mm.TimeLength) + 1);
    finally
      mm.FreeStream;
      mm.Free;
    end;
    ShellExecute(0, 'open', PChar(myConst.SilentPlay),
      PChar(Format('%s %s "%s"', [sec, aVolume, AFileName])), nil, SW_HIDE);
  except
    on e: Exception do
      TTW_Bot.toLog( 'TSongMachine', 'PlaySilent', e.message,2)
  end;
end;

procedure TSongMachine.PlayPublic(AFileName: string; aVolume: string);
begin
  try
    if not FileExists(AFileName) then
    begin
      TTW_Bot.toLog( 'TSongMachine', 'PlayPublic', 'Нет файла ' + AFileName,2);
      exit;
    end;
    mp.Volume := strtoint(aVolume);
    mp.Play(AFileName)
  except
    on e: Exception do
      TTW_Bot.toLog( 'TSongMachine', 'PlaySilent', e.message,2)
  end;
end;

end.
