Title: Programmatically Get and Set the MediaPlayer Sound Volume
The TMediaPlayer Delphi component enables your application to control a media playing or recording device such as a CD-ROM player, video player/recorder.
Here's how to get / set the sound volume while the media is being played in the Media Player.
uses
MMSystem;
const
MCI_SETAUDIO = $0873;
MCI_DGV_SETAUDIO_VOLUME = $4002;
MCI_DGV_SETAUDIO_ITEM = $00800000;
MCI_DGV_SETAUDIO_VALUE = $01000000;
MCI_DGV_STATUS_VOLUME = $4019;
type
MCI_DGV_SETAUDIO_PARMS = record
dwCallback: DWORD;
dwItem: DWORD;
dwValue: DWORD;
dwOver: DWORD;
lpstrAlgorithm: PChar;
lpstrQuality: PChar;
end;
type
MCI_STATUS_PARMS = record
dwCallback: DWORD;
dwReturn: DWORD;
dwItem: DWORD;
dwTrack: DWORD;
end;
{Set Volume, range 0 - 1000}
procedure MPSetVolume(MP: TMediaPlayer; Volume: Integer) ;
var
p: MCI_DGV_SETAUDIO_PARMS;
begin
p.dwCallback := 0;
p.dwItem := MCI_DGV_SETAUDIO_VOLUME;
p.dwValue := Volume;
p.dwOver := 0;
p.lpstrAlgorithm := nil;
p.lpstrQuality := nil;
mciSendCommand(MP.DeviceID, MCI_SETAUDIO, MCI_DGV_SETAUDIO_VALUE or MCI_DGV_SETAUDIO_ITEM, Cardinal(@p)) ;
end;
{Get Volume, range 0 - 1000}
function MPGetVolume(MP: TMediaPlayer): Integer;
var
p: MCI_STATUS_PARMS;
begin
p.dwCallback := 0;
p.dwItem := MCI_DGV_STATUS_VOLUME;
mciSendCommand(MP.DeviceID, MCI_STATUS, MCI_STATUS_ITEM, Cardinal(@p)) ;
Result := p.dwReturn;
end;
Usage: drop a TMediaPlayer ("MediaPlayer1") along with a TScrollBar ("ScrollBar1") on Delphi form.
In the OnCreate event for the form, setup the scroll bar and load a media file into MediaPlayer:
procedure TMediaPlayerForm.FormCreate(Sender: TObject) ;
begin
ScrollBar1.Min := 0;
ScrollBar1.Max := 1000;
ScrollBar1.Position := MPGetVolume(MediaPlayer1);
MediaPlayer1.Close;
MediaPlayer1.FileName:='c:\favorite.mp3';
MediaPlayer1.Open;
end;
Handle the OnChange event of the scroll bar (to set the Media player volume):
procedure TMediaPlayerForm.ScrollBar1Change(Sender: TObject) ;
begin
MPSetVolume(MediaPlayer1, ScrollBar1.Position) ;
end;
Note: The related articles box features more TMediaPlayer tutorials and tips.