这是一个简单的经过测试的例子,用TMediaPlayer播放音乐的同时,点击Button2来同步播放背景音乐。
unit utMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, MPlayer;
type
TForm1 = class(TForm)
MediaPlayer1: TMediaPlayer;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
utPlaySoundThread;
procedure TForm1.Button1Click(Sender: TObject);
begin
MediaPlayer1.FileName := 'D:/MyProgram/Delphi/Temp/01.mp3';
MediaPlayer1.Open;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
ps:TPlaySound;
begin
ps := TPlaySound.Create(False);
end;
end.
*************************播放背景音乐的线程
unit utPlaySoundThread;
interface
uses
Classes, Mmsystem;
type
TPlaySound = class(TThread)
private
{ Private declarations }
protected
procedure Execute;
override;
procedure Play;
end;
implementation
{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TPlaySound.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
}
{ TPlaySound }
procedure TPlaySound.Play;
begin
PlaySound('D:/MyProgram/Delphi/Temp/music.wav',1,SND_ASYNC);
end;
procedure TPlaySound.Execute;
begin
{ Place thread code here }
Synchronize(Play);
end;
end.