How to get the master volume in windows xp?

末鹿安然 提交于 2019-11-29 10:59:59

The below is a little modification on the example code found here (credited there is Thomas Stutz). The example there sets the microphone volume. I just modified the component type - speaker destination instead of microphone source, and replaced mixerSetControlDetails with mixerGetControlDetails, and turned the setter into a getter of course. On the few systems I tested here (XPSp3, XPSp2, W2K, 98), it seems to work. The return of the function is the speaker out of the first (default) mixer - a value of 0-65535, the 'ShowMessage' in the button handler changes it into a percentage. But don't ask me more details about it, I really have no experience with the mixer api. Instead refer here f.i., though old the article really seemed to be comprehensive to me.

function GetSpeakerVolume(var bValue: Word): Boolean;
var                          {0..65535}
  hMix: HMIXER;
  mxlc: MIXERLINECONTROLS;
  mxcd: TMIXERCONTROLDETAILS;
  vol: TMIXERCONTROLDETAILS_UNSIGNED;
  mxc: MIXERCONTROL;
  mxl: TMixerLine;
  intRet: Integer;
  nMixerDevs: Integer;
begin
  Result := False;

  // Check if Mixer is available
  nMixerDevs := mixerGetNumDevs();
  if (nMixerDevs < 1) then
    Exit;

  // open the mixer
  intRet := mixerOpen(@hMix, 0, 0, 0, 0);
  if intRet = MMSYSERR_NOERROR then
  begin
    mxl.dwComponentType := MIXERLINE_COMPONENTTYPE_DST_SPEAKERS;
    mxl.cbStruct := SizeOf(mxl);

    // get line info
    intRet := mixerGetLineInfo(hMix, @mxl, MIXER_GETLINEINFOF_COMPONENTTYPE);

    if intRet = MMSYSERR_NOERROR then
    begin
      ZeroMemory(@mxlc, SizeOf(mxlc));
      mxlc.cbStruct := SizeOf(mxlc);
      mxlc.dwLineID := mxl.dwLineID;
      mxlc.dwControlType := MIXERCONTROL_CONTROLTYPE_VOLUME;
      mxlc.cControls := 1;
      mxlc.cbmxctrl := SizeOf(mxc);

      mxlc.pamxctrl := @mxc;
      intRet := mixerGetLineControls(hMix, @mxlc, MIXER_GETLINECONTROLSF_ONEBYTYPE);

      if intRet = MMSYSERR_NOERROR then
      begin
        ZeroMemory(@mxcd, SizeOf(mxcd));
        mxcd.dwControlID := mxc.dwControlID;
        mxcd.cbStruct := SizeOf(mxcd);
        mxcd.cMultipleItems := 0;
        mxcd.cbDetails := SizeOf(vol);
        mxcd.paDetails := @vol;
        mxcd.cChannels := 1;

        intRet := mixerGetControlDetails(hMix, @mxcd, MIXER_GETCONTROLDETAILSF_VALUE);
        if intRet <> MMSYSERR_NOERROR then
          ShowMessage('GetControlDetails Error')
        else begin
          bValue := vol.dwValue;
          Result := True;
        end;
      end
      else
        ShowMessage('GetLineInfo Error');
    end;
    intRet := mixerClose(hMix);
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  Vol: Word;
begin
  if GetSpeakerVolume(Vol) then
    ShowMessage(IntToStr(Round(Vol * 100 / 65535)));
end;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!