---
title: "Handle audio device loss in C#"
url: https://recursiveai.org/oneaudio/cookbook/handle-audio-device-loss/
description: "Observe device-loss and recovery events, inspect silent-rendering counters, and choose an output device with the oneaudio Devices package in C#."
version: "1.7.2"
---

# Handle audio device loss in C#

**oneaudio** is a free, open-source audio library for .NET from Recursive AI. MIT or Apache-2.0, no bundled native binaries.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneAudio.Devices) · [GitHub](https://github.com/recursive-ai-oss/oneaudio-csharp) · [Docs](https://recursiveai.org/oneaudio/docs/) · [Download example (.zip)](https://recursiveai.org/oneaudio/cookbook/handle-audio-device-loss/handle-audio-device-loss.zip)

On disconnect, the output keeps rendering silently and retries opening the device automatically; watch `DeviceLost`, `DeviceRestored` and `Reopened`. The downloadable sample simulates the device so it runs without hardware.

```shell
dotnet add package RecursiveAI.OneAudio.Devices
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneAudio.Devices;

var backend = new ManualBackend();
using var output = AudioOutputDevice.Open(
    (Span<float> s, in RenderContext c) =>
        s.Clear(), null, backend);
output.Start();
backend.SimulateLoss();
output.Pump();
while (output.TryGetEvent(out var item))
    Console.WriteLine(item.Kind);
```

Unzip [the example](https://recursiveai.org/oneaudio/cookbook/handle-audio-device-loss/handle-audio-device-loss.zip), then `dotnet run`.

Prints:

```text
DeviceLost
Reopened
```

## The full program

The snippet at the top uses the public `ManualBackend`: it loses a device and immediately reopens it. The full program also refuses one reopen, renders silence while unavailable, waits for a retry, follows a default-device change and explicitly selects the original device. The output below is from this offline path, not a physical unplug test.

`Pump()`, `Advance(480)`, `FailOpens(1)` and `Thread.Sleep` drive the simulated device and its retry test; they aren’t needed with real hardware.

```csharp
using OneAudio.Devices;

var backend = new ManualBackend();
using var output = AudioOutputDevice.Open(
    (Span<float> samples, in RenderContext context) => samples.Clear(),
    new DeviceStreamOptions { FollowDefault = true }, backend);
output.Start();
output.Advance(480);
backend.FailOpens(1);
backend.SimulateLoss();
output.Pump();
Console.WriteLine($"After loss: {output.State}");
output.Advance(960);
Thread.Sleep(600);
output.Pump();
Console.WriteLine($"After retry: {output.State}");
backend.SetDefault("manual-out-1");
output.Pump();
output.SelectDevice("manual-out-0");
Console.WriteLine($"Selected: {output.Device?.Id}");
while (output.TryGetEvent(out var item)) Console.WriteLine(item.Kind);
var counters = output.Counters;
Console.WriteLine($"Losses: {counters.DeviceLosses}, reopens: {counters.Reopens}");
Console.WriteLine($"Rendered: {counters.FramesRendered}, written: {counters.FramesWritten}");
Console.WriteLine($"Discarded silent frames: {counters.SilentFrames}");
```

`dotnet run` prints:

```text
After loss: NoDevice
After retry: Running
Selected: manual-out-0
DeviceLost
DeviceRestored
DefaultChanged
Reopened
Reopened
Losses: 1, reopens: 3
Rendered: 1440, written: 480
Discarded silent frames: 960
```

When a device cannot open, the stream keeps rendering silently and records the reason in `LastError`; it retries twice a second.

## Variations

**Open the real default output device**

Omit the backend argument to `AudioOutputDevice.Open`, then call `Start`. This selects the operating system’s backend and the default output; `FollowDefault` is true by default. The library handles reopening; the polling loop below reports loss, restoration, reopening and default-device changes. It runs for three seconds and renders silence, so it makes no audible sound.

The pinned [device documentation](https://recursiveai.org/oneaudio/docs/api/#devices-recursiveaioneaudiodevices) lists “Core Audio (macOS and iOS)”, “AAudio (Android)”, “ALSA (Linux)” and “WASAPI (Windows)”. ALSA has no hot-plug events: its backend detects a lost device through write errors rather than `DevicesChanged` notifications.

```csharp
using OneAudio.Devices;

// No backend argument: use the operating system's backend.
using var output = AudioOutputDevice.Open(
    (Span<float> samples, in RenderContext context) => samples.Clear());
output.Start();
Console.WriteLine($"Backend: {output.BackendName}");
DateTime stop = DateTime.UtcNow.AddSeconds(3);
while (DateTime.UtcNow < stop)
{
    while (output.TryGetEvent(out var item))
        if (item.Kind is DeviceEventKind.DeviceLost
            or DeviceEventKind.DeviceRestored
            or DeviceEventKind.Reopened
            or DeviceEventKind.DefaultChanged)
            Console.WriteLine($"{item.Kind}: {output.State}");
    await Task.Delay(100);
}
Console.WriteLine($"State: {output.State}");
Console.WriteLine($"Frames written: {output.Counters.FramesWritten}");
Console.WriteLine($"Last error: {output.LastError ?? "none"}");
```

This ran with the real ALSA backend on Linux and printed the following; no physical unplug/replug was performed. Frame totals depend on scheduling, and a disconnect during the loop adds event lines.

```text
Backend: alsa
State: Running
Frames written: 144720
Last error: none
```

If the default device cannot open, `State` becomes `NoDevice` and `LastError` explains why; the output keeps retrying. Keep the output alive for as long as playback is needed rather than disposing it after the three-second demonstration.

**Select a device explicitly**

Ignore system-default changes and switch only when your application chooses:

```csharp
using OneAudio.Devices;

var backend = new ManualBackend();
using var output = AudioOutputDevice.Open(
    (Span<float> s, in RenderContext c) => s.Clear(),
    new DeviceStreamOptions { FollowDefault = false }, backend);
output.Start();
backend.SetDefault("manual-out-1");
output.Pump();
Console.WriteLine(output.Device?.Id);
output.SelectDevice("manual-out-1");
Console.WriteLine(output.Device?.Id);
```

```text
manual-out-0
manual-out-1
```

## Related recipes

[List audio devices](https://recursiveai.org/oneaudio/cookbook/list-audio-devices/)

---

## The short answer

Use `RecursiveAI.OneAudio.Devices` and observe `DeviceLost`, `DeviceRestored` and `Reopened` through `TryGetEvent` or the `Event` subscription. Leave the output alive during a disconnect: it renders silently while no device is available and retries opening twice a second. Recreating it on every notification is not required for this recovery path.

The download exercises recovery using `ManualBackend`, a public backend without hardware. It makes loss and reopening repeatable. It does not establish that a particular USB headset, driver or Bluetooth connection will recover correctly on your machine. Test those separately with the actual operating-system backend and the device your application supports.

## How do I detect when an audio device has been unplugged in C#?

Poll `TryGetEvent` on the output as shown in the full program. Events carry device IDs and the played-frame count at the time of the event. The alternative `Event` callback is raised on the supervisor thread. Neither notification mechanism should be confused with the render callback, which runs on the real-time device thread.

Do not allocate, lock or block in the render callback. The sample simply clears an already supplied span, producing silence. If a render callback throws, the package catches the exception, increments `CallbackFaults` in the counters, and plays that block as silence. Put user-interface updates and diagnostic formatting outside that callback.

The manual backend has no supervisor thread. Its `Pump` method handles pending recovery and default-device notifications; `Advance` drives rendering by an explicit frame count. Real backends supervise devices themselves. Do not copy the manual test’s sleep into a real-time callback: the wait is outside rendering and only lets the test reach the documented retry interval.

## How do I reset the audio output device?

For an application-level change, call `SelectDevice` with an ID returned by device enumeration. The variation selects a manual device explicitly. This is not a Windows driver reset or a driver installation tool. If your operating system cannot see the hardware, the library cannot repair that underlying installation.

`DeviceStreamOptions.DeviceId` selects the initial device. A null ID means the system default; `FollowDefault` defaults to true. Set it to false when your application must keep its chosen destination rather than follow another application or the user changing the default. The full program shows both automatic default following and a later explicit selection.

Read counters instead of treating `Running` as proof that sound was heard. `FramesRendered` counts source work; `FramesWritten` counts frames handed to the device; `FramesPlayed` comes from the device’s position and never exceeds frames written. During unavailable-device rendering, the source clock continues but those frames are discarded. In this test 960 such frames are counted as `SilentFrames`. The source is deliberately silent even while the device is open, so the run demonstrates recovery state, not audible playback.

Source: [oneaudio device documentation](https://recursiveai.org/oneaudio/docs/api/#devices-recursiveaioneaudiodevices).
