Delphi component for monitoring audio device changes using Windows Core Audio API. Detects changes like switching from PC speakers to headphones.
- Duplicate Event Prevention: Filters multiple events for same device change
- Configurable Timeout: EventFilterTimeout property (default 500ms)
- Smart Detection: Only triggers on actual device changes, not Windows internal events
- HRESULT checks for all COM calls
- Exception handling and error logging
- LastError property for error tracking
- Initialize function for safe startup
- UI events run on main thread (TThread.Queue)
- Crash protection in COM callbacks
- Safe event calling mechanism
- OnDefaultDeviceChanged: Default device switched
- OnDeviceAdded: New device added
- OnDeviceRemoved: Device removed
- OnDeviceStateChanged: Device state changed
- OnPropertyValueChanged: Device properties changed
- OnAnyDeviceChanged: Any device change
- TAudioDeviceInfo struct with rich device info
- Device friendly name retrieval
- Device ID, Flow, Role, State information
- Default device detection
- GetCurrentDefaultDevice(): Get current default device
- GetAllAudioDevices(): List all audio devices
- IsDeviceActive(): Check device active status
- Initialize(): Manual initialization
- DataFlowToString(): Convert Render/Capture to string
- RoleToString(): Console/Multimedia/Communications info
- DeviceStateToString(): Active/Disabled/Unplugged states
- PropVariant cleanup
- Proper cleanup for COM objects
- CoTaskMemFree to prevent memory leaks
- Device state constants (DEVICE_STATE_ACTIVE etc.)
- Property key definitions (PKEY_Device_FriendlyName)
- PropVariant type constants (VT_LPWSTR etc.)
AudioMonitor := TAudioDeviceMonitor.Create(Self);
AudioMonitor.OnDefaultDeviceChanged := MyDeviceChangeHandler;
AudioMonitor.EventFilterTimeout := 300; // Optional: 300ms filter timeout
procedure TForm1.MyDeviceChangeHandler(Sender: TObject; const DeviceInfo: TAudioDeviceInfo);
begin
ShowMessage('Audio device changed: ' + DeviceInfo.DeviceName);
end;The enhanced version provides better reliability for detecting audio device changes like switching from speakers to headphones, with proper error handling, thread-safe event notifications, and intelligent event filtering to prevent duplicate notifications.