2010-12-21 50 views
5

在Windows XP中,用Delphi,如何獲得主音量?如何在Windows XP中獲得主卷?

我知道我可以通過keybd_event(VK_VOLUME_UP, 1, 0, 0);keybd_event(VK_VOLUME_DOWN, 1, 0, 0);來設置和發送擊鍵,但我不知道如何獲得音量的實際值。

+0

這個問題沒有什麼特別與德爾福,但只有Windows API。此鏈接可能有所幫助:http://blogs.msdn.com/b/alejacma/archive/2010/01/13/how-to-set-sound-volume-programmatically.aspx – 2010-12-22 00:35:02

+0

我不是說這必須與delphi一起,但我想知道_ how_這個_with_ delphi。 – eKek0 2010-12-22 00:41:07

回答

3

以下是對發現的示例代碼here(相信有Thomas Stutz)的一些修改。這裏的例子設置麥克風音量。我只是修改了組件類型 - 揚聲器目標而不是麥克風源,並且用mixerGetControlDetails替換mixerSetControlDetails,並且當然將setter變成吸氣劑。在我測試的少數幾個系統上(XPSp3,XPSp2,W2K,98),似乎可行。函數返回的是第一個(默認)混音器中的揚聲器 - 值爲0-65535,按鈕處理程序中的「ShowMessage」將其更改爲百分比。但是不要問我更多關於它的細節,我真的沒有使用混音器API的經驗。相反,請參閱here f.i.,儘管這篇文章對我來說似乎很全面。

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;