Repository navigation
Expand file tree
/
Copy pathKasmMic.cs
More file actions
174 lines (156 loc) · 6.33 KB
/
Copy pathKasmMic.cs
File metadata and controls
174 lines (156 loc) · 6.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
using System;
using System.Drawing;
using System.Windows.Forms;
using NAudio.Wave;
using System.Management;
using System.Threading.Tasks;
using System.Linq;
namespace KasmMicApp
{
public class KasmMic : Form
{
private NotifyIcon trayIcon;
private WaveInEvent waveIn;
private Icon quietIcon;
private Icon activeIcon;
private ManagementEventWatcher deviceWatcher;
private bool restartScheduled = false;
public KasmMic()
{
// Hide the window
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
this.Opacity = 0;
this.Load += (s, e) => this.Hide();
// Load icons (replace with actual icons)
quietIcon = new Icon("quiet.ico"); // Path to the custom icon
activeIcon = new Icon("active.ico"); // Path to the custom icon
// Setup Tray Icon
trayIcon = new NotifyIcon
{
Icon = quietIcon,
Visible = true,
Text = "Microphone Monitor"
};
// Context Menu
var contextMenu = new ContextMenuStrip();
contextMenu.Items.Add("Exit", null, OnExit);
trayIcon.ContextMenuStrip = contextMenu;
// Setup Microphone Listener
// Setup Microphone Listener
InitializeMicrophone();
// Handle device changes
StartDeviceWatcher();
}
private bool IsRemoteAudioReady()
{
try
{
var searcher = new ManagementObjectSearcher("SELECT Name, Status FROM Win32_PnPEntity WHERE PNPClass='AudioEndpoint'");
var devices = searcher.Get().Cast<ManagementObject>();
return devices.Any(d => d["Name"] != null && d["Status"] != null && d["Name"].ToString().IndexOf("Remote", StringComparison.OrdinalIgnoreCase) >= 0 && d["Status"].ToString() == "OK");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error checking remote audio status: " + ex.Message);
return false;
}
}
private void InitializeMicrophone()
{
System.Diagnostics.Debug.WriteLine("Initializing microphone...");
// Get the number of available input devices
if (!IsRemoteAudioReady() || WaveIn.DeviceCount == 0)
{
System.Diagnostics.Debug.WriteLine("No microphone detected. Retrying in 5 seconds...");
Task.Delay(5000).ContinueWith(_ => RestartMicrophone());
return;
}
try
{
if (waveIn != null)
{
waveIn.StopRecording();
waveIn.Dispose();
waveIn = null;
}
waveIn = new WaveInEvent
{
DeviceNumber = 0, // Use the default microphone
WaveFormat = new WaveFormat(44100, 1) // 44.1 kHz, Mono
};
waveIn.DataAvailable += OnAudioData;
waveIn.StartRecording();
System.Diagnostics.Debug.WriteLine("Microphone started.");
}
catch (NAudio.MmException ex)
{
System.Diagnostics.Debug.WriteLine($"NAudio Error: {ex.Message}");
System.Diagnostics.Debug.WriteLine("Retrying in 5 seconds...");
Task.Delay(5000).ContinueWith(_ => RestartMicrophone());
}
catch (AccessViolationException ex)
{
System.Diagnostics.Debug.WriteLine($"Access Violation Error: {ex.Message}");
System.Diagnostics.Debug.WriteLine("Likely RDP session disconnection. Retrying in 5 seconds...");
Task.Delay(5000).ContinueWith(_ => RestartMicrophone());
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Unexpected error: {ex.Message}");
}
}
private void RestartMicrophone()
{
System.Diagnostics.Debug.WriteLine("Microphone device change detected. Restarting microphone...");
InitializeMicrophone();
}
private void StartDeviceWatcher()
{
System.Diagnostics.Debug.WriteLine("Starting device watcher...");
deviceWatcher = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 OR EventType = 3"));
deviceWatcher.EventArrived += (sender, e) =>
{
//System.Diagnostics.Debug.WriteLine("Device change event detected:");
//foreach (var property in e.NewEvent.Properties)
//{
// System.Diagnostics.Debug.WriteLine($"{property.Name}: {property.Value}");
//}
if (!restartScheduled)
{
restartScheduled = true;
System.Diagnostics.Debug.WriteLine("Audio device change detected! Restarting microphone in 5 seconds...");
RestartMicrophone();
Task.Delay(5000).ContinueWith(_ => restartScheduled = false);
}
else
{
System.Diagnostics.Debug.WriteLine("Additional audio device change detected within cooldown period, ignoring...");
}
};
deviceWatcher.Start();
}
private void OnAudioData(object sender, WaveInEventArgs e)
{
float maxVolume = 0;
for (int i = 0; i < e.BytesRecorded; i += 2)
{
short sample = (short)(e.Buffer[i] | (e.Buffer[i + 1] << 8));
float volume = Math.Abs(sample / 32768f);
if (volume > maxVolume)
maxVolume = volume;
}
// Update tray icon based on noise level
trayIcon.Icon = maxVolume > 0.05f ? activeIcon : quietIcon;
}
private void OnExit(object sender, EventArgs e)
{
waveIn.StopRecording();
waveIn.Dispose();
trayIcon.Dispose();
Application.Exit();
}
}
}