uses Windows, MMDeviceApi, ComObj, ActiveX, Classes, SysUtils; type TForm1 = class(TForm) private FDeviceEnumerator: IMMDeviceEnumerator; FEndpointVolume: IAudioEndpointVolume; FHeadphoneConnected: Boolean; procedure CheckHeadphoneStatus; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation constructor TForm1.Create(AOwner: TComponent); begin inherited Create(AOwner); CoInitialize(nil); FDeviceEnumerator := CreateComObject(CLASS_MMDeviceEnumerator) as IMMDeviceEnumerator; CheckHeadphoneStatus; end; destructor TForm1.Destroy; begin FDeviceEnumerator := nil; FEndpointVolume := nil; CoUninitialize; inherited Destroy; end; procedure TForm1.CheckHeadphoneStatus; var Device: IMMDevice; State: DWORD; begin FDeviceEnumerator.GetDefaultAudioEndpoint(eRender, eMultimedia, Device); if Assigned(Device) then begin Device.GetState(State); if State = DEVICE_STATE_ACTIVE then FHeadphoneConnected := True else FHeadphoneConnected := False; // 여기에서 이어폰 연결 상태에 따른 추가 작업을 수행할 수 있습니다. if FHeadphoneConnected then ShowMessage('Headphones are connected') else ShowMessage('Headphones are not connected'); end; end; end.
DirectX를 이용한 방법
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DirectSound; type TForm1 = class(TForm) Button1: TButton; Label1: TLabel; procedure Button1Click(Sender: TObject); private { Private declarations } FDirectSound: IDirectSound; function IsHeadphonesConnected: Boolean; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin if IsHeadphonesConnected then Label1.Caption := 'Headphones are connected' else Label1.Caption := 'Headphones are not connected'; end; function TForm1.IsHeadphonesConnected: Boolean; var DSCaps: TDSCAPS; begin Result := False; if DirectSoundCreate(nil, FDirectSound, nil) = DS_OK then begin ZeroMemory(@DSCaps, SizeOf(DSCaps)); DSCaps.dwSize := SizeOf(DSCaps); if FDirectSound.GetCaps(DSCaps) = DS_OK then begin if (DSCaps.dwFlags and DSCAPS_PRIMARYMONO <> 0) or (DSCaps.dwFlags and DSCAPS_PRIMARYSTEREO <> 0) then begin Result := True; // Assume headphones are connected if a primary sound device is available end; end; FDirectSound := nil; end; end; end.