Mirror

Changing Position of Current Played Track in TMediaPlayer (Views: 717)


Problem/Question/Abstract:

Difficulties in moving forward/backward (changing position) the current played track in TMediaPlayer ??

Answer:

To change the current position of current playing track, you just need to take the usefull (advance) of two event: 1) onTimer of TTimer and 2) onChange of TScrollbar. For full code, read below.

Here are the codes:

procedure TForm1.Button1Click(Sender: TObject);
begin
  if (OpenDialog1.Execute) then
  begin
    Timer1.Enabled := false;
    MediaPlayer1.FileName := OpenDialog1.FileName;
    MediaPlayer1.Open;
    ScrollBar1.Max := MediaPlayer1.Length;
    ScrollBar1.Position := 0;
    Timer1.Enabled := true;
  end;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  ScrollBar1.OnChange := nil; // disable the event handler
  ScrollBar1.Position := MediaPlayer1.Position;
  ScrollBar1.OnChange := ScrollBar1Change; // enable it again
end;

procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
  MediaPlayer1.Pause;
  MediaPlayer1.Position := ScrollBar1.Position;
  MediaPlayer1.Play;
end;

First thing you must do here is initiate the MAX range of TScrollBar with the length of the current song track (look at Button1Click above).

Then add onTimer event code like above, and so the onChange event of TScrollBar.
The key is you must set TMediaPlayer's position with your selected scroolbar position for each of onTimer happen. Do this by calling onChange event of TScrollBar in onTimer event of TTimer.

<< Back to main page