4

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

Nyt Ryda
  • 335
  • 2
  • 4
  • 9
  • 1
    possible duplicate of [How to play a wav-File in Delphi?](http://stackoverflow.com/questions/246723/how-to-play-a-wav-file-in-delphi) You don't really need the MediaPlayerComponent, you can also use the MMSystem unit, see the link. – Johan Oct 14 '11 at 09:59
  • @Johan Does that also work for `wma` and `mp3`? – NGLN Oct 14 '11 at 10:04
  • I used the TMediaPlayer and it works but after the length of the song, it does not repeat the song. How do I get the song to repeat ? – Nyt Ryda Oct 14 '11 at 13:43
  • @NGLN, annoyingly sometimes it does and sometimes it does not. On my old laptop WinXP-xp3 it works with MP3's and on a VM-copy of my pre-pre laptop Win XP sp1 it does not. – Johan Oct 14 '11 at 20:11

2 Answers2

6

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.

NGLN
  • 43,011
  • 8
  • 105
  • 200
  • Some editions of Windows (N versions) in Europe have no MediaPlayer. So you have to list it as requirement in the install script. – Fabricio Araujo Oct 14 '11 at 18:21
  • 2
    You don't need to run the Timer while the audio is playing. Set the `TMediaPlayer.Notify` property to true before calling `Play()`, then use the `OnNotify` event to detect when playback stops. Then start the timer for 1s and call `Play()` when it elapses. – Remy Lebeau Aug 03 '19 at 08:15
2

You can use TMediaPlayerComponent.
Here you can find a tutorial on how to use it.

Marco
  • 56,740
  • 14
  • 129
  • 152