Make sure sessions get removed and add more logging
Deploy to Gitea Releases / deploy-to-gitea-releases (push) Successful in 37s

This commit is contained in:
2026-08-25 15:42:24 -04:00
parent 46fce20771
commit a55ef1f27e
7 changed files with 192 additions and 115 deletions
+88
View File
@@ -0,0 +1,88 @@
using NAudio.CoreAudioApi;
using NAudio.CoreAudioApi.Interfaces;
using Serilog;
using System.Collections.Generic;
using System.Linq;
namespace WorkIndicator.Audio;
internal class AudioDevice
{
private readonly ILogger _logger;
public delegate void AudioSessionsChangedDelegate();
public event AudioSessionsChangedDelegate AudioSessionsChanged;
public bool IsMuted { get; private set; }
public string FriendlyName { get; }
public Dictionary<string, AudioSession> Sessions { get; } = new();
public AudioDevice(MMDevice device)
{
_logger = Log.ForContext<AudioDevice>();
FriendlyName = device.DeviceFriendlyName;
IsMuted = device.AudioEndpointVolume.Mute;
_logger.Information("AudioDevice: {name} {muted}", FriendlyName, IsMuted);
device.AudioEndpointVolume.OnVolumeNotification += AudioEndpointVolume_OnVolumeNotification;
device.AudioSessionManager.OnSessionCreated += AudioSessionManager_OnSessionCreated;
device.AudioSessionManager.RefreshSessions();
var sessions = device.AudioSessionManager.Sessions;
for (var i = 0; i < sessions.Count; i++)
{
SetupSession(sessions[i]);
}
}
private void AudioEndpointVolume_OnVolumeNotification(AudioVolumeNotificationData data)
{
_logger.Information("AudioEndpointVolume_OnVolumeNotification: {name} {muted}", FriendlyName, data.Muted);
IsMuted = data.Muted;
AudioSessionsChanged?.Invoke();
}
private void AudioSessionManager_OnSessionCreated(object sender, IAudioSessionControl newSession)
{
var session = new AudioSessionControl(newSession);
_logger.Information("OnSessionCreated: {name}", session.GetSessionIdentifier);
SetupSession(session);
}
private void SetupSession(AudioSessionControl session)
{
_logger.Information("SetupSession: {name}", session.GetSessionIdentifier);
var audioSession = new AudioSession(session, FriendlyName);
Sessions[session.GetSessionIdentifier] = audioSession;
audioSession.AudioSessionChanged += AudioSession_AudioSessionChanged;
AudioSessionsChanged?.Invoke();
}
private void AudioSession_AudioSessionChanged(string id, AudioSessionState state)
{
_logger.Information("AudioSessionChanged: {id} {state}", id, state);
AudioSessionsChanged?.Invoke();
if (state == AudioSessionState.AudioSessionStateExpired)
{
Sessions.Remove(id);
}
}
public int ActiveSessionCount => Sessions.Values.Count(s => s.State == AudioSessionState.AudioSessionStateActive);
}
+70
View File
@@ -0,0 +1,70 @@
using NAudio.CoreAudioApi;
using NAudio.CoreAudioApi.Interfaces;
using Serilog;
using System;
namespace WorkIndicator.Audio;
internal class AudioSession : IAudioSessionEventsHandler
{
private readonly ILogger _logger;
private readonly AudioSessionControl _audioSessionControl;
public string Id { get; }
public string FriendlyName { get; }
public delegate void AudioSessionChangedDelegate(string id, AudioSessionState state);
public event AudioSessionChangedDelegate AudioSessionChanged;
public AudioSession(AudioSessionControl audioSessionControl, string friendlyName)
{
_logger = Log.ForContext<AudioSession>();
_audioSessionControl = audioSessionControl;
Id = audioSessionControl.GetSessionIdentifier;
FriendlyName = friendlyName;
audioSessionControl.RegisterEventClient(this);
}
public AudioSessionState State => _audioSessionControl.State;
void IAudioSessionEventsHandler.OnVolumeChanged(float volume, bool isMuted)
{
_logger.Information("OnVolumeChanged: {name} {volume} {isMuted}", FriendlyName, volume, isMuted);
}
void IAudioSessionEventsHandler.OnDisplayNameChanged(string displayName)
{
_logger.Information("OnDisplayNameChanged: {name}", displayName);
}
void IAudioSessionEventsHandler.OnIconPathChanged(string iconPath)
{
_logger.Information("OnIconPathChanged: {path}", iconPath);
}
void IAudioSessionEventsHandler.OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex)
{
_logger.Information("OnChannelVolumeChanged: {channelCount} {newVolumes} {channelIndex}", channelCount, newVolumes, channelIndex);
}
void IAudioSessionEventsHandler.OnGroupingParamChanged(ref Guid groupingId)
{
_logger.Information("OnGroupingParamChanged: {groupingId}", groupingId);
}
void IAudioSessionEventsHandler.OnStateChanged(AudioSessionState state)
{
_logger.Information("OnStateChanged: {state}", state);
AudioSessionChanged?.Invoke(Id, state);
}
void IAudioSessionEventsHandler.OnSessionDisconnected(AudioSessionDisconnectReason disconnectReason)
{
_logger.Information("OnSessionDisconnected: {disconnectReason}", disconnectReason);
}
}
+140
View File
@@ -0,0 +1,140 @@
using NAudio.CoreAudioApi;
using NAudio.CoreAudioApi.Interfaces;
using Serilog;
using System.Collections.Generic;
namespace WorkIndicator.Audio;
internal enum MicrophoneStatus
{
NotUsed,
UsedMuted,
UsedNotMuted
}
internal class AudioWatcher : IMMNotificationClient
{
private readonly ILogger _logger = Log.ForContext<AudioWatcher>();
private readonly MMDeviceEnumerator _deviceEnumerator = new();
private readonly Dictionary<string, AudioDevice> _inputDevices = new();
public delegate void MicrophoneStatusChangedDelegate(MicrophoneStatus microphoneStatus);
public event MicrophoneStatusChangedDelegate MicrophoneStatusChanged;
public void Start()
{
_logger.Information("Start");
_deviceEnumerator.RegisterEndpointNotificationCallback(this);
_logger.Information("Getting capture devices");
var captureDevices = _deviceEnumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
foreach (var captureDevice in captureDevices)
{
_logger.Information("Capture device: {name}", captureDevice.DeviceFriendlyName);
HandleAddedDevice(captureDevice);
}
}
public void LogState()
{
_logger.Information("---");
foreach (var inputDevicePair in _inputDevices)
{
_logger.Information("Device: {name} {muted}", inputDevicePair.Value.FriendlyName, inputDevicePair.Value.IsMuted);
foreach (var sessionPair in inputDevicePair.Value.Sessions)
{
var session = sessionPair.Value;
_logger.Information("Session: {id} {friendlyName} {state}", session.Id, session.FriendlyName, session.State);
}
}
_logger.Information("---");
}
private void HandleAddedDevice(MMDevice captureDevice)
{
_logger.Information("Device added: {name}", captureDevice.DeviceFriendlyName);
var audioDevice = new AudioDevice(captureDevice);
audioDevice.AudioSessionsChanged += AudioDevice_AudioSessionsChanged;
_inputDevices[captureDevice.ID] = audioDevice;
MicrophoneStatusChanged?.Invoke(GetMicrophoneStatus());
}
private void AudioDevice_AudioSessionsChanged()
{
MicrophoneStatusChanged?.Invoke(GetMicrophoneStatus());
}
private void HandleRemovedDevice(string deviceId)
{
_logger.Information("Device removed: {id}", deviceId);
_inputDevices.Remove(deviceId);
MicrophoneStatusChanged?.Invoke(GetMicrophoneStatus());
}
public void Stop()
{
_logger.Information("Stop");
_deviceEnumerator.UnregisterEndpointNotificationCallback(this);
_deviceEnumerator.Dispose();
}
public MicrophoneStatus GetMicrophoneStatus()
{
foreach (var inputDevice in _inputDevices.Values)
{
if (inputDevice.ActiveSessionCount > 0)
return inputDevice.IsMuted ? MicrophoneStatus.UsedMuted : MicrophoneStatus.UsedNotMuted;
}
return MicrophoneStatus.NotUsed;
}
void IMMNotificationClient.OnDeviceStateChanged(string deviceId, DeviceState newState)
{
_logger.Information("OnDeviceStateChanged: {deviceId} {newState}", deviceId, newState);
}
void IMMNotificationClient.OnDeviceAdded(string deviceId)
{
_logger.Information("OnDeviceAdded: {deviceId}", deviceId);
var device = _deviceEnumerator.GetDevice(deviceId);
if (device.DataFlow is DataFlow.Capture or DataFlow.All)
{
HandleAddedDevice(device);
}
}
void IMMNotificationClient.OnDeviceRemoved(string deviceId)
{
_logger.Information("OnDeviceRemoved: {deviceId}", deviceId);
HandleRemovedDevice(deviceId);
}
void IMMNotificationClient.OnDefaultDeviceChanged(DataFlow flow, Role role, string defaultDeviceId)
{
_logger.Information("OnDefaultDeviceChanged: {defaultDeviceId} {flow} {role}", defaultDeviceId, flow, role);
}
void IMMNotificationClient.OnPropertyValueChanged(string pwstrDeviceId, PropertyKey key)
{
_logger.Debug("OnPropertyValueChanged: {deviceId} {propertyId}", pwstrDeviceId, key.propertyId);
}
}