procedure TForm1.SetMasterVolumeLevelScalar(Level: Single);
var
MuteStatus: Boolean;
FAudioEndpointVolume: AudioEndpoint.IAudioEndpointVolume;
// from the Andreas Rejbrand unit
begin
//try
if not Succeeded(CoCreateInstance(CLASS_IMMDeviceEnumerator,
nil, CLSCTX_INPROC_SERVER, IID_IMMDeviceEnumerator, FDeviceEnumerator))
then
begin
CodeSite.Send('
TForm1.SetMasterVolumeLevelScalar: 1');
ExitProcess(1);
end;
if not Succeeded(FDeviceEnumerator.GetDefaultAudioEndpoint(0, 0, FMMDevice))
then
begin
CodeSite.Send('
TForm1.SetMasterVolumeLevelScalar: 2');
ExitProcess(1);
end;
if not Succeeded(FMMDevice.Activate(IID_IAudioEndpointVolume, CLSCTX_INPROC_SERVER,
nil, FAudioEndpointVolume))
then
begin
CodeSite.Send('
TForm1.SetMasterVolumeLevelScalar: 3');
ExitProcess(1);
end;
if not Succeeded(FAudioEndpointVolume.RegisterControlChangeNotify(Self))
then
begin
CodeSite.Send('
TForm1.SetMasterVolumeLevelScalar: 4');
ExitProcess(1);
end;
if Assigned(FAudioEndpointVolume)
then
begin
// Get the current mute status
FAudioEndpointVolume.GetMute(MuteStatus);
// Unmute if it was muted:
if MuteStatus
then
FAudioEndpointVolume.SetMute(False,
nil);
// This line is executed, but the master volume is NOT unmuted!
// Ensure the level is within the valid range (0.0 to 1.0):
Level := Max(0.0, Min(1.0, Level));
// Set the master volume level as a scalar:
FAudioEndpointVolume.SetMasterVolumeLevelScalar(Level,
nil);
// it works!
// Optionally, you can send a notification or update your UI here
end
else
begin
CodeSite.Send('
TForm1.SetMasterVolumeLevelScalar: FAudioEndpointVolume not assigned!');
end;
{except
on E: Exception do
begin
// Handle any exceptions here
CodeSite.Send('Exception in SetMasterVolumeLevelScalar', E.Message);
end;
end;}
end;