feat: mix music and microphone on one program output

Songs and the microphone now go through one audio channel,
ProgramOutput, instead of each opening its own device. ProgramMixer
builds two mixes in one pass: the broadcast for the listeners and a
monitor mix for the person at the desk. With two playback devices each
mix gets its own device; with one device the desk hears the monitor
mix.

The Schedule page gets a microphone button that works with or without
a running broadcast, and sliders for the music and microphone levels
on the broadcast, the music level on the monitor, and an option to
hear the broadcast exactly. The Settings page lets the user choose
the playback devices for the broadcast and for themselves.

MusicPlayer plays its tracks into the mixer; pause takes the track
out of the mix and resume puts it back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Opus 5.5 committed 2026-11-25 08:21:13 +01:00
1 parent 2380f233b5
commit 5d261717fe
14 files changed
+829 -89

No files matched your search

+6
View File
@@ -32,6 +32,12 @@ public record AppSettings
/// <summary>Target; the plan gets as close as the song lengths allow.</summary>
public int AdMinutesPerHour { get; init; } = 20;
/// <summary>Playback device for the listeners; <c>null</c> is the Windows default device.</summary>
public string? BroadcastDevice { get; init; }
/// <summary>Playback device for the person at the desk; <c>null</c> means no device of its own.</summary>
public string? MonitorDevice { get; init; }
public static string DefaultPath { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json");
+58
View File
@@ -0,0 +1,58 @@
using NAudio.Wave;
namespace Radiosender.Services;
/// <summary>Puts the default recording device on air through the <see cref="ProgramOutput"/>, so the speaker can talk over or between items.</summary>
public sealed class Microphone(ProgramOutput output) : IDisposable
{
private readonly Lock _lock = new();
private WaveIn? _capture;
private ISampleProvider? _input;
public bool IsOn
{
get { lock (_lock) return _capture is not null; }
}
/// <exception cref="InvalidOperationException">No microphone or no output device can be opened; the message can be shown to the user.</exception>
public void TurnOn()
{
lock (_lock)
{
if (_capture is not null)
return;
if (WaveIn.DeviceCount == 0)
throw new InvalidOperationException("Es wurde kein Mikrofon gefunden.");
var capture = new WaveIn { WaveFormat = new WaveFormat(44100, 16, 1), BufferMilliseconds = 30 };
// A short buffer that drops what it cannot hold: speech must not fall further and further behind.
var buffer = new BufferedWaveProvider(capture.WaveFormat, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true };
capture.DataAvailable += (_, e) => buffer.AddSamples(e.Buffer, 0, e.BytesRecorded);
try
{
capture.StartRecording();
_input = output.Add(buffer.ToSampleProvider(), AudioSource.Microphone);
}
catch (Exception e) when (e is NAudio.MmException or NotSupportedException)
{
capture.Dispose();
throw new InvalidOperationException($"Das Mikrofon konnte nicht eingeschaltet werden: {e.Message}", e);
}
_capture = capture;
}
}
public void TurnOff()
{
lock (_lock)
{
if (_input is not null)
output.Remove(_input);
_input = null;
_capture?.Dispose(); // stops the recording
_capture = null;
}
}
public void Dispose() => TurnOff();
}
+33 -31
View File
@@ -4,7 +4,7 @@ using NAudio.Wave;
namespace Radiosender.Services;
/// <summary>
/// Plays one audio file at a time through the default output device.
/// Plays one audio file at a time on the <see cref="ProgramOutput"/>, the station's audio channel.
/// </summary>
/// <remarks>
/// <see cref="TrackFinished"/> and <see cref="PositionChanged"/> are raised on a thread-pool thread,
@@ -17,15 +17,19 @@ public sealed class MusicPlayer : IAudioPlayer
private static readonly TimeSpan PositionInterval = TimeSpan.FromMilliseconds(250);
private readonly ProgramOutput _output = ProgramOutput.Instance;
private readonly Lock _lock = new();
private WaveOut? _output;
private AudioFileReader? _reader;
private ISampleProvider? _input; // the reader as it sits in the mixer; null while paused
private Timer? _positionTimer;
private float _volume = 1f;
private MusicPlayer()
{
// Releases the audio device when the app exits.
// The mixer reports the end of a track on the audio thread, which must not wait for _lock:
// Stop holds _lock while it waits for that thread. So the work moves to the thread pool.
_output.InputEnded += (_, input) => ThreadPool.QueueUserWorkItem(_ => OnInputEnded(input));
// Releases the file when the app exits.
AppDomain.CurrentDomain.ProcessExit += (_, _) => Stop();
}
@@ -39,7 +43,7 @@ public sealed class MusicPlayer : IAudioPlayer
public bool IsPlaying
{
get { lock (_lock) return _output?.PlaybackState == PlaybackState.Playing; }
get { lock (_lock) return _input is not null; }
}
public TimeSpan Position
@@ -52,7 +56,10 @@ public sealed class MusicPlayer : IAudioPlayer
get { lock (_lock) return _reader?.TotalTime ?? TimeSpan.Zero; }
}
/// <summary>Playback volume from 0 (silent) to 1 (full). Kept across tracks.</summary>
/// <summary>
/// Volume of the music from 0 (silent) to 1 (full), before it reaches the mixer, so it applies to listeners and
/// monitor alike. Kept across tracks; the microphone is not affected.
/// </summary>
public float Volume
{
get { lock (_lock) return _volume; }
@@ -85,25 +92,20 @@ public sealed class MusicPlayer : IAudioPlayer
try
{
_reader = new AudioFileReader(filePath) { Volume = _volume };
_input = _output.Add(_reader, AudioSource.Music);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
catch (Exception ex) when (ex is not (OutOfMemoryException or NAudio.MmException))
{
Release();
throw new InvalidDataException($"Audiodatei kann nicht gelesen werden: {filePath}", ex);
}
try
{
_output = new WaveOut();
_output.PlaybackStopped += OnPlaybackStopped;
_output.Init(_reader);
_output.Play();
_positionTimer = new Timer(OnPositionTimer, null, PositionInterval, PositionInterval);
}
catch
{
Release();
Release(); // no output device: the file must not stay open
throw;
}
_positionTimer = new Timer(OnPositionTimer, null, PositionInterval, PositionInterval);
}
}
@@ -111,7 +113,9 @@ public sealed class MusicPlayer : IAudioPlayer
{
lock (_lock)
{
if (_output?.PlaybackState == PlaybackState.Playing) _output.Pause();
if (_input is null) return;
_output.Remove(_input);
_input = null;
}
}
@@ -119,45 +123,43 @@ public sealed class MusicPlayer : IAudioPlayer
{
lock (_lock)
{
if (_output?.PlaybackState == PlaybackState.Paused) _output.Play();
if (_reader is not null && _input is null) _input = _output.Add(_reader, AudioSource.Music);
}
}
/// <summary>Stops playback and releases the file and audio device. Does not raise <see cref="TrackFinished"/>.</summary>
/// <summary>Stops playback and releases the file. Does not raise <see cref="TrackFinished"/>.</summary>
public void Stop()
{
lock (_lock) Release();
}
// Caller holds _lock. Unsubscribing first keeps Stop and track replacement from raising TrackFinished.
// Caller holds _lock. Clearing _input first keeps Stop and track replacement from raising TrackFinished.
private void Release()
{
_positionTimer?.Dispose();
_positionTimer = null;
if (_output is not null)
if (_input is not null)
{
_output.PlaybackStopped -= OnPlaybackStopped;
_output.Dispose();
_output = null;
// Returns once the audio thread has let go of the reader, so disposing it below is safe.
_output.Remove(_input);
_input = null;
}
_reader?.Dispose();
_reader = null;
}
private void OnPlaybackStopped(object? sender, StoppedEventArgs e)
private void OnInputEnded(ISampleProvider input)
{
lock (_lock)
{
// A stale event from an output that Stop or Play already released.
if (!ReferenceEquals(sender, _output)) return;
// Another input of the channel, or a track that Stop or Play already replaced.
if (!ReferenceEquals(input, _input)) return;
Release();
}
// An exception means a device error, not a natural end of the track.
if (e.Exception is null)
ThreadPool.QueueUserWorkItem(_ => TrackFinished?.Invoke(this, EventArgs.Empty));
TrackFinished?.Invoke(this, EventArgs.Empty);
}
private void OnPositionTimer(object? state)
@@ -165,7 +167,7 @@ public sealed class MusicPlayer : IAudioPlayer
TimeSpan position;
lock (_lock)
{
if (_output?.PlaybackState != PlaybackState.Playing || _reader is null) return;
if (_input is null || _reader is null) return;
position = _reader.CurrentTime;
}
+102
View File
@@ -0,0 +1,102 @@
using NAudio.Wave;
namespace Radiosender.Services;
/// <summary>What an input of the mixer is; the levels differ by kind.</summary>
public enum AudioSource
{
Music,
Microphone,
}
/// <summary>
/// Mixes every input twice in one pass: once for the listeners (the broadcast) and once for the person at
/// the desk (the monitor). Each input is read only once, so both mixes stay in step.
/// </summary>
public sealed class ProgramMixer
{
private readonly Lock _lock = new();
private readonly List<(ISampleProvider Input, AudioSource Kind)> _inputs = [];
private float[] _scratch = [];
// Written by the UI thread, read by the audio thread; a level that arrives one block late is fine.
private volatile float _musicForOthers = 1f;
private volatile float _microphoneForOthers = 1f;
private volatile float _musicForMe = 1f;
private volatile bool _listenToBroadcast = true;
/// <summary>
/// Raised when an input has played to its end and was dropped. Comes from the audio thread while the
/// mixer is busy: handlers must return at once and must not call back into the mixer.
/// </summary>
public event EventHandler<ISampleProvider>? InputEnded;
/// <summary>How loud the music is on the broadcast, from 0 to 1.</summary>
public float MusicForOthers { get => _musicForOthers; set => _musicForOthers = Level(value); }
/// <summary>How loud the microphone is on the broadcast, from 0 to 1.</summary>
public float MicrophoneForOthers { get => _microphoneForOthers; set => _microphoneForOthers = Level(value); }
/// <summary>How loud the music is on the monitor, from 0 to 1. The monitor never carries the microphone: hearing oneself late is distracting.</summary>
public float MusicForMe { get => _musicForMe; set => _musicForMe = Level(value); }
/// <summary>When set, the monitor is an exact copy of the broadcast and <see cref="MusicForMe"/> has no effect.</summary>
public bool ListenToBroadcast { get => _listenToBroadcast; set => _listenToBroadcast = value; }
public void Add(ISampleProvider input, AudioSource kind)
{
lock (_lock) _inputs.Add((input, kind));
}
/// <summary>Returns once the audio thread no longer reads from the input.</summary>
public void Remove(ISampleProvider input)
{
lock (_lock) _inputs.RemoveAll(entry => ReferenceEquals(entry.Input, input));
}
/// <summary>Fills both buffers, which must have the same length, with the next block of each mix.</summary>
public void Mix(Span<float> broadcast, Span<float> monitor)
{
broadcast.Clear();
monitor.Clear();
if (_scratch.Length < broadcast.Length)
_scratch = new float[broadcast.Length];
var block = _scratch.AsSpan(0, broadcast.Length);
var copyBroadcast = _listenToBroadcast;
lock (_lock)
{
for (var i = _inputs.Count - 1; i >= 0; i--)
{
var (input, kind) = _inputs[i];
var read = input.Read(block);
var forOthers = kind == AudioSource.Music ? _musicForOthers : _microphoneForOthers;
var forMe = kind == AudioSource.Music ? _musicForMe : 0f;
for (var n = 0; n < read; n++)
{
broadcast[n] += block[n] * forOthers;
monitor[n] += block[n] * forMe;
}
if (read < block.Length)
{
_inputs.RemoveAt(i);
InputEnded?.Invoke(this, input);
}
}
}
// Two loud inputs can add up past full scale, which would distort harshly on the device.
for (var n = 0; n < broadcast.Length; n++)
{
broadcast[n] = Math.Clamp(broadcast[n], -1f, 1f);
monitor[n] = copyBroadcast ? broadcast[n] : Math.Clamp(monitor[n], -1f, 1f);
}
}
private static float Level(float value)
{
ArgumentOutOfRangeException.ThrowIfLessThan(value, 0f);
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 1f);
return value;
}
}
+187
View File
@@ -0,0 +1,187 @@
using System.Runtime.InteropServices;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
namespace Radiosender.Services;
/// <summary>
/// The station's audio channel: everything that goes on air (songs, the microphone) is mixed here.
/// The broadcast mix plays on one device for the listeners. A second device, if one is chosen, plays
/// the monitor mix for the person at the desk; without it the one device plays the monitor mix.
/// Cues for the speaker only, like the alert tone and the import preview, stay off this channel.
/// </summary>
public sealed class ProgramOutput
{
private static readonly Lazy<ProgramOutput> LazyInstance = new(() => new ProgramOutput());
/// <summary>All inputs are converted to this format before mixing.</summary>
public static WaveFormat Format { get; } = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2);
private readonly Lock _lock = new();
private string? _broadcastName;
private string? _monitorName;
private bool _started;
private WaveOut? _broadcastDevice;
private WaveOut? _monitorDevice;
private ProgramOutput()
{
Mixer.InputEnded += (_, input) => InputEnded?.Invoke(this, input);
// Releases the audio devices when the app exits.
AppDomain.CurrentDomain.ProcessExit += (_, _) => { lock (_lock) CloseDevices(); };
}
public static ProgramOutput Instance => LazyInstance.Value;
/// <summary>The levels of both mixes.</summary>
public ProgramMixer Mixer { get; } = new();
/// <summary>Same as <see cref="ProgramMixer.InputEnded"/>: raised on the audio thread, handlers must return at once.</summary>
public event EventHandler<ISampleProvider>? InputEnded;
/// <summary>Names of the playback devices Windows offers, for the settings page.</summary>
public static IReadOnlyList<string> DeviceNames() =>
Enumerable.Range(0, WaveOut.DeviceCount).Select(i => WaveOut.GetCapabilities(i).ProductName).ToList();
/// <summary>
/// Chooses the devices by name: <c>null</c> for the broadcast means the Windows default device,
/// <c>null</c> for the monitor means no device of its own. Devices that are already open are reopened.
/// A name that no longer exists counts as <c>null</c>.
/// </summary>
/// <exception cref="NAudio.MmException">A device cannot be opened.</exception>
public void UseDevices(string? broadcast, string? monitor)
{
lock (_lock)
{
_broadcastName = broadcast;
_monitorName = monitor;
if (!_started)
return;
CloseDevices();
OpenDevices();
}
}
/// <summary>Puts a source on air and opens the output devices on first use.</summary>
/// <returns>The input as the mixer knows it; pass it to <see cref="Remove"/> and compare it in <see cref="InputEnded"/>.</returns>
/// <exception cref="NotSupportedException">The source has more than two channels.</exception>
/// <exception cref="NAudio.MmException">No audio output device can be opened.</exception>
public ISampleProvider Add(ISampleProvider source, AudioSource kind)
{
var input = ToProgramFormat(source);
lock (_lock)
{
if (!_started)
{
OpenDevices();
_started = true;
}
}
Mixer.Add(input, kind);
return input;
}
/// <summary>Takes an input off air. Returns once the audio thread no longer reads from it.</summary>
public void Remove(ISampleProvider input) => Mixer.Remove(input);
/// <summary>Converts mono to stereo and any sample rate to the channel's 44.1 kHz.</summary>
public static ISampleProvider ToProgramFormat(ISampleProvider source)
{
if (source.WaveFormat.Channels > 2)
throw new NotSupportedException("Audio with more than two channels is not supported.");
if (source.WaveFormat.Channels == 1)
source = new MonoToStereoSampleProvider(source);
if (source.WaveFormat.SampleRate != Format.SampleRate)
source = new WdlResamplingSampleProvider(source, Format.SampleRate);
return source;
}
// Caller holds _lock.
private void OpenDevices()
{
var names = DeviceNames().ToList();
var broadcast = _broadcastName is null ? -1 : names.IndexOf(_broadcastName); // -1 is the Windows default device
var monitor = _monitorName is null ? -1 : names.IndexOf(_monitorName);
// The same device twice would only play both mixes on top of each other.
if (monitor == broadcast || (broadcast == -1 && monitor == 0 && names.Count == 1))
monitor = -1;
try
{
if (monitor < 0)
{
// One device: the person at the desk hears the monitor mix; nothing is sent anywhere else.
_broadcastDevice = Open(broadcast, new Tap(Mixer, null));
}
else
{
// The broadcast device sets the pace. Each block it asks for also yields the monitor block,
// which waits in a short buffer for the second device. The buffer drops what it cannot hold,
// so the two device clocks drifting apart never builds up a delay.
var monitorBuffer = new BufferedWaveProvider(Format, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true };
_broadcastDevice = Open(broadcast, new Tap(Mixer, monitorBuffer));
_monitorDevice = Open(monitor, monitorBuffer.ToSampleProvider());
}
}
catch
{
CloseDevices();
throw;
}
}
private static WaveOut Open(int deviceNumber, ISampleProvider source)
{
// Three buffers of 50 ms: short enough that live speech does not lag noticeably.
var device = new WaveOut { DeviceNumber = deviceNumber, BufferMilliseconds = 50, NumberOfBuffers = 3 };
try
{
device.Init(source);
device.Play();
return device;
}
catch
{
device.Dispose();
throw;
}
}
// Caller holds _lock.
private void CloseDevices()
{
_broadcastDevice?.Dispose();
_broadcastDevice = null;
_monitorDevice?.Dispose();
_monitorDevice = null;
}
/// <summary>
/// What the pacing device plays. With a monitor buffer it plays the broadcast mix and feeds the buffer;
/// without one it plays the monitor mix itself.
/// </summary>
private sealed class Tap(ProgramMixer mixer, BufferedWaveProvider? monitorBuffer) : ISampleProvider
{
private float[] _other = [];
public WaveFormat WaveFormat => Format;
public int Read(Span<float> buffer)
{
if (_other.Length < buffer.Length)
_other = new float[buffer.Length];
var other = _other.AsSpan(0, buffer.Length);
if (monitorBuffer is null)
{
mixer.Mix(other, buffer);
}
else
{
mixer.Mix(buffer, other);
monitorBuffer.AddSamples(MemoryMarshal.AsBytes(other));
}
return buffer.Length; // never ends: silence while nothing is on air
}
}
}
+21 -3
View File
@@ -2,28 +2,46 @@ namespace Radiosender.Services;
/// <summary>
/// The current <see cref="AppSettings"/> for the whole app. Loads them at startup and, on every save,
/// writes the file and hands the minutes per hour to the schedule generator.
/// writes the file and hands the minutes per hour to the schedule generator and the devices to the audio output.
/// </summary>
public class SettingsStore
{
private readonly ScheduleGenerator _generator;
private readonly ProgramOutput _output;
private readonly string _path;
public SettingsStore(ScheduleGenerator generator, string path)
public SettingsStore(ScheduleGenerator generator, ProgramOutput output, string path)
{
_generator = generator;
_output = output;
_path = path;
Current = AppSettings.Load(path);
_generator.Options = Current.ToScheduleOptions();
// Nothing is open yet at startup, so this cannot fail here.
_output.UseDevices(Current.BroadcastDevice, Current.MonitorDevice);
}
public AppSettings Current { get; private set; }
/// <summary>Stores the settings and applies them: alerts at once, minutes per hour from the next plan on.</summary>
/// <summary>Stores the settings and applies them: alerts and audio devices at once, minutes per hour from the next plan on.</summary>
/// <exception cref="System.IO.IOException">The settings file cannot be written.</exception>
/// <exception cref="UnauthorizedAccessException">The settings file cannot be written.</exception>
/// <exception cref="NAudio.MmException">A chosen audio device cannot be opened; nothing was saved.</exception>
public void Save(AppSettings settings)
{
// Devices first: if one cannot be opened, the old settings stay in the file.
if (settings.BroadcastDevice != Current.BroadcastDevice || settings.MonitorDevice != Current.MonitorDevice)
{
try
{
_output.UseDevices(settings.BroadcastDevice, settings.MonitorDevice);
}
catch (NAudio.MmException)
{
_output.UseDevices(Current.BroadcastDevice, Current.MonitorDevice);
throw;
}
}
settings.Save(_path);
Current = settings;
_generator.Options = settings.ToScheduleOptions();