Teams microphone detection
Detect an active Windows capture session belonging to Teams and use that signal for automation. This is a heuristic, not meeting detection: device tests can trigger it, muting can change it, and browser-based Teams is not identified.
Run it
Requires Windows, .NET 10 SDK and NAudio 3.3.0. Save Program.cs and TeamsMicrophone.csproj into an empty folder:
dotnet run
Default: detection only, with visible status and no recording. Press Ctrl+C to stop.
Optional recording
dotnet run -- --record
Type RECORD at the prompt to enable capture with permission. Status is shown in the console; WAV files stay in Documents/PromicroRecordings. Capture uses the detected microphone, follows device changes and waits for final buffers before closing the file.
This records the local microphone, not the full Teams conversation or other participants. It is not Teams’ built-in recording feature. Validate it with your Teams client and devices before relying on it.
dotnet run -- --self-test checks process names without accessing microphones. Compilation and these checks have passed; live Teams detection and audio capture have not been exercised here.
Built with NAudio; see its recording lifecycle guidance.
Complete source
using System.Diagnostics;
using System.Runtime.InteropServices;
using NAudio.CoreAudioApi;
using NAudio.CoreAudioApi.Interfaces;
using NAudio.Wave;
// Pure checks: no device enumeration, capture or file creation.
if (args.Contains("--self-test"))
{
if (!IsTeamsProcess("MS-TEAMS") || !IsTeamsProcess("Teams") ||
IsTeamsProcess("not-teams") || IsTeamsProcess("chrome"))
throw new InvalidOperationException("Process-name checks failed.");
Console.WriteLine("Process-name checks passed. No audio was captured.");
return;
}
if (!OperatingSystem.IsWindows())
throw new PlatformNotSupportedException("This example requires Windows.");
bool record = args.Contains("--record");
if (record)
{
Console.WriteLine("Records the detected microphone locally, not the full Teams conversation.");
Console.Write("Only proceed with permission to record. Type RECORD to enable: ");
if (Console.ReadLine() != "RECORD") return;
}
using var cancellation = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; cancellation.Cancel(); };
Console.WriteLine(record ? "Recording enabled. Ctrl+C stops and saves." :
"Detection only. No audio is recorded. Ctrl+C to exit.");
string? previous = null;
try
{
while (!cancellation.IsCancellationRequested)
{
var microphone = FindTeamsMicrophone();
string status = microphone is null ? "No active Teams capture session." :
$"Teams microphone active: {microphone.Name}";
if (status != previous) { Console.WriteLine(status); previous = status; }
if (record && microphone is not null)
await RecordWhileActive(microphone, cancellation.Token);
else
await Task.Delay(1000, cancellation.Token);
}
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested) { }
catch (Exception e) when (e is COMException or IOException or UnauthorizedAccessException)
{
Console.Error.WriteLine($"Stopped: {e.Message}");
Environment.ExitCode = 1;
}
static Microphone? FindTeamsMicrophone()
{
using var audio = new MMDeviceEnumerator();
using var devices = audio.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
foreach (var device in devices)
{
using (device)
{
try
{
var sessions = device.AudioSessionManager.Sessions;
for (int i = 0; i < sessions.Count; i++)
{
using var session = sessions[i];
if (IsActiveTeamsSession(session))
return new Microphone(device.ID, device.FriendlyName);
}
}
catch (COMException e)
{
// Endpoints can disappear during enumeration. Retry next poll.
Console.Error.WriteLine($"Skipping unavailable microphone: {e.Message}");
}
}
}
return null;
}
static bool IsActiveTeamsSession(AudioSessionControl session)
{
if (session.State != AudioSessionState.AudioSessionStateActive)
return false;
try
{
using var process = Process.GetProcessById((int)session.GetProcessID);
return IsTeamsProcess(process.ProcessName);
}
catch (ArgumentException) { return false; } // Process exited.
catch (System.ComponentModel.Win32Exception) { return false; }
}
static bool IsTeamsProcess(string name) =>
name.Equals("ms-teams", StringComparison.OrdinalIgnoreCase) ||
name.Equals("teams", StringComparison.OrdinalIgnoreCase);
static async Task RecordWhileActive(Microphone microphone, CancellationToken token)
{
using var audio = new MMDeviceEnumerator();
using var device = audio.GetDevice(microphone.Id);
using var formatClient = device.CreateAudioClient();
var format = formatClient.MixFormat;
using var capture = new WasapiRecorderBuilder().WithDevice(device).WithFormat(format).Build();
string folder = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "PromicroRecordings");
Directory.CreateDirectory(folder);
string file = Path.Combine(folder, $"voice-{DateTime.UtcNow:yyyyMMdd-HHmmss}-{Guid.NewGuid():N}.wav");
using var writer = new WaveFileWriter(file, format);
var stopped = new TaskCompletionSource<Exception?>(TaskCreationOptions.RunContinuationsAsynchronously);
Exception? writeError = null;
capture.DataAvailable += (buffer, _, _, _) =>
{
if (Volatile.Read(ref writeError) is not null) return;
try { writer.Write(buffer); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ Interlocked.CompareExchange(ref writeError, ex, null); }
};
capture.RecordingStopped += (_, e) => stopped.TrySetResult(e.Exception);
capture.StartRecording();
Console.WriteLine($"RECORDING microphone: {microphone.Name}\nFile: {file}");
try
{
while (!stopped.Task.IsCompleted && Volatile.Read(ref writeError) is null &&
FindTeamsMicrophone()?.Id == microphone.Id)
await Task.Delay(1000, token);
}
finally
{
capture.StopRecording();
// Drain final buffers before disposing the writer and finalizing the WAV.
var captureError = await stopped.Task;
var error = Volatile.Read(ref writeError) ?? captureError;
if (error is not null) throw new IOException("Microphone recording failed.", error);
Console.WriteLine("Recording stopped; finalizing WAV file.");
}
}
record Microphone(string Id, string Name);