Search code examples
delphiwindows-vistawindows-xpmediavolume

how to adjust master volume in vista/xp


i want to adjust the volume programatically like Get/SetMasterVolume in vista and xp? using mmsystem unit?


Solution

  • Here's the implementation of a general purpose api for audio: MMDevApi

    http://social.msdn.microsoft.com/Forums/en/windowspro-audiodevelopment/thread/5ce74d5d-2b1e-4ca9-a8c9-2e27eb9ec058

    and an example with a button

    unit Unit33;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, MMDevApi, ActiveX, StdCtrls;
    
    type
      TForm33 = class(TForm)
        Button1: TButton;
        procedure FormCreate(Sender: TObject);
        procedure Button1Click(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;
    
    var
      Form33: TForm33;
      endpointVolume: IAudioEndpointVolume = nil;
    
    implementation
    
    {$R *.dfm}
    
    
    procedure TForm33.Button1Click(Sender: TObject);
    var
      VolumeLevel: Single;
    begin
      if endpointVolume = nil then Exit;
      VolumeLevel := 0.50;
      endpointVolume.SetMasterVolumeLevelScalar(VolumeLevel, nil);
      Caption := Format('%1.8f', [VolumeLevel])
    end;
    
    procedure TForm33.FormCreate(Sender: TObject);
    var
      deviceEnumerator: IMMDeviceEnumerator;
      defaultDevice: IMMDevice;
    begin
      CoCreateInstance(CLASS_IMMDeviceEnumerator, nil, CLSCTX_INPROC_SERVER, IID_IMMDeviceEnumerator, deviceEnumerator);
      deviceEnumerator.GetDefaultAudioEndpoint(eRender, eConsole, defaultDevice);
      defaultDevice.Activate(IID_IAudioEndpointVolume, CLSCTX_INPROC_SERVER, nil, endpointVolume);
    end;
    
    end.