How to get music to play in Delphi 7?

Nyt Ryda picture Nyt Ryda · Oct 14, 2011 · Viewed 9.1k times · Source

I need to get music to play in the background in the start of the program in the OnFormActivate event for my program. I have the song I want to use but I dont know what command Delphi needs to use in order to start playing that song.

Thanks for you help guys :)

Answer

NGLN picture NGLN · Oct 14, 2011

Use the TMediaPlayer component, it's on the System tab of the component palette.

procedure TForm1.FormActivate(Sender: TObject);
begin
  MediaPlayer1.FileName := '<fill in>.mp3';
  MediaPlayer1.Open;
  MediaPlayer1.Play;
end;

Set the Visible property to False.


Edit in response to OP's comment:

To repeat the song, you can use the TTimer component, also found on the System tab. To repeat the song with a one second delay:

procedure TForm1.FormActivate(Sender: TObject);
begin
  MediaPlayer1.FileName := '<fill in>.mp3';
  MediaPlayer1.Open;
  MediaPlayer1.TimeFormat := tfMilliseconds;
  Timer1.Interval := MediaPlayer1.Length + 1000;
  MediaPlayer1.Play;
  Timer1.Enabled := True;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  MediaPlayer1.Play;
end;

Set the timer's Enabled property to False.