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:
1 parent
2380f233b5
commit
5d261717fe
14 files changed
+829
-89
No files matched your search
@@ -7,6 +7,7 @@ WPF desktop app that plans and plays a radio program for a chosen number of full
|
||||
- Windows
|
||||
- .NET SDK 10
|
||||
- An audio output device for playback
|
||||
- A microphone, if you want to talk on air
|
||||
|
||||
## Build and run
|
||||
|
||||
@@ -38,9 +39,11 @@ The interface is in German. This section names the controls as they appear on sc
|
||||
3. **Start** puts the plan on air on the real clock. Before the planned start the now-playing card shows when the broadcast begins; if the plan has already begun, playback joins at the next item. The same button then reads **Stopp** and ends it. The now-playing card shows the current item, its progress and the volume.
|
||||
4. **Edit the timeline**: select an upcoming row and use the buttons above the list to move it up or down, edit it, or remove it (trash icon). News, ad and moderator items have no title until you give them one; news and moderator items can also change their length. A double-click opens the editor too. Every item after a change follows on without a gap. The item on air can be edited too, but not moved or removed; **Jetzt beenden** in the now-playing card ends it at once and starts the next item.
|
||||
5. **Speaking reminder**: 30 seconds before a news or moderator item goes on air, a dialog in the middle of the screen reminds you on any page and stays until you click **OK**.
|
||||
6. **Songwunsch**: choose a song, select an upcoming row in the timeline and click **Auswahl ersetzen**. This also works while the broadcast is running.
|
||||
6. **Microphone**: **Mikro ein** in the now-playing card puts the default microphone on air, also over running music; the button turns red and reads **Mikro aus**. It works with or without a broadcast and stays on while you visit other pages.
|
||||
7. **Mix levels**, below the now-playing row: **Musik für andere** and **Ich für andere** set how loud the music and the microphone are for the listeners, **Musik für mich** how loud the music is on your own device. **Sendung 1:1 hören** lets you hear exactly what the listeners hear. The slider next to the loudspeaker stays the overall music volume.
|
||||
8. **Songwunsch**: choose a song, select an upcoming row in the timeline and click **Auswahl ersetzen**. This also works while the broadcast is running.
|
||||
|
||||
4. **Einstellungen** (bottom left): switch the speaking alert on or off for news and for moderator talk, set how many seconds before the start it appears and whether it plays a bing sound. Set the minutes per hour for news, moderator talk and ads (defaults 10, 10 and 20); together they can take at most 60 minutes. **ZurĂĽcksetzen** puts the default values into the form, **Speichern** stores them in `settings.json` next to the database. Alerts change at once; minutes per hour apply to the next schedule.
|
||||
4. **Einstellungen** (bottom left): switch the speaking alert on or off for news and for moderator talk, set how many seconds before the start it appears and whether it plays a bing sound. Choose the playback device for the broadcast (for the listeners) and, if you have a second one such as headphones, the device for yourself. Set the minutes per hour for news, moderator talk and ads (defaults 10, 10 and 20); together they can take at most 60 minutes. **ZurĂĽcksetzen** puts the default values into the form, **Speichern** stores them in `settings.json` next to the database. Alerts change at once; minutes per hour apply to the next schedule.
|
||||
|
||||
News, ads and moderator talk are placeholders: the app shows them in the timeline and keeps silent for their duration, so the speaker can talk live.
|
||||
|
||||
@@ -76,7 +79,10 @@ Main services:
|
||||
- `SongImportService`: copies an uploaded file into the music folder, reads its tags with TagLibSharp and its duration with NAudio
|
||||
- `IMusicProvider`: an online catalog that can be searched. `OpenverseProvider` uses the anonymous Openverse API and `InternetArchiveProvider` the Internet Archive search, limited to Creative Commons licensed MP3 files.
|
||||
- `TrackDownloader`: downloads a search result into the music folder, the same way for every provider
|
||||
- `MusicPlayer`: the audio player as a singleton (`MusicPlayer.Instance`, private constructor). It plays files with NAudio.
|
||||
- `ProgramMixer`: mixes songs and the microphone twice in one pass, once for the listeners and once for the person at the desk, each with its own levels
|
||||
- `ProgramOutput`: the station's audio channel. It plays the broadcast mix on one device and, if a second device is chosen, the monitor mix on that one
|
||||
- `MusicPlayer`: the audio player as a singleton (`MusicPlayer.Instance`, private constructor). It reads files with NAudio and plays them on the `ProgramOutput`
|
||||
- `Microphone`: captures the default recording device and puts it on the `ProgramOutput`
|
||||
- `ScheduleGenerator`: builds the plan and handles song requests
|
||||
- `PlaybackEngine`: runs the plan item by item on a background thread and plays songs through `MusicPlayer`
|
||||
|
||||
@@ -128,5 +134,7 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a
|
||||
- **Internet Archive**: one search asks for up to 8 items and then for the file list of each, and shows at most 5 MP3 files per item. Results can include long recordings; the 50 MB download limit applies.
|
||||
- **Very old libraries**: a `radiosender.db` from before the Openverse import has no `OpenverseId` column and is not upgraded. Delete the file and import the music again.
|
||||
- **Deleting a song** removes it from the library but keeps its file in the `Music` folder.
|
||||
- **Placeholders** have no audio.
|
||||
- **Placeholders** have no audio; news and moderator talk are spoken live through the microphone.
|
||||
- **Microphone**: uses the default Windows recording device. With loudspeakers next to the microphone the room hears itself and can start to howl, so use headphones. Speech arrives about a fifth of a second late. The alert tone and the import preview are not part of the program channel.
|
||||
- **Two mixes need two devices**: with one playback device you hear your own mix, or the broadcast mix while **Sendung 1:1 hören** is on, and nobody else hears anything different. Your own mix never contains the microphone. With two devices their clocks can drift, which shows as a rare tiny dropout on the second device. The mix levels are not stored and start at full on every launch.
|
||||
- **Targets** for ads and moderator talk are missed by the time the songs cannot fill, usually a few seconds per hour; a small library or only long songs make that more.
|
||||
@@ -20,8 +20,12 @@ public partial class App : Application
|
||||
// so a running broadcast keeps going while the user switches pages.
|
||||
services.AddSingleton(_ => new SongRepository(SongRepository.DefaultDatabasePath));
|
||||
services.AddSingleton(_ => new ScheduleGenerator());
|
||||
services.AddSingleton(provider => new SettingsStore(provider.GetRequiredService<ScheduleGenerator>(), AppSettings.DefaultPath));
|
||||
services.AddSingleton(provider => new SettingsStore(
|
||||
provider.GetRequiredService<ScheduleGenerator>(), provider.GetRequiredService<ProgramOutput>(), AppSettings.DefaultPath));
|
||||
services.AddSingleton(_ => new PlaybackEngine());
|
||||
// The one audio channel that songs and the microphone share.
|
||||
services.AddSingleton(_ => ProgramOutput.Instance);
|
||||
services.AddSingleton<Microphone>();
|
||||
services.AddSingleton(provider => new ScheduleController(
|
||||
provider.GetRequiredService<SongRepository>(),
|
||||
provider.GetRequiredService<ScheduleGenerator>(),
|
||||
@@ -57,7 +61,7 @@ public partial class App : Application
|
||||
{
|
||||
base.OnStartup(e);
|
||||
_services = BuildServices();
|
||||
// Loads the settings and gives the generator its minutes per hour before the first plan.
|
||||
// Loads the settings: the generator gets its minutes per hour before the first plan, the audio output its devices.
|
||||
_services.GetRequiredService<SettingsStore>();
|
||||
// Follow the Windows setting: light, dark or a high-contrast theme.
|
||||
Wpf.Ui.Appearance.ApplicationThemeManager.ApplySystemTheme();
|
||||
|
||||
@@ -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");
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -94,47 +94,47 @@
|
||||
IsClosable="True"
|
||||
IsOpen="False" />
|
||||
|
||||
<!-- Now playing -->
|
||||
<!-- Now playing: what is on air and its buttons on top, the mixing desk below -->
|
||||
<Border Grid.Row="3"
|
||||
Margin="0,16,0,16"
|
||||
Padding="16"
|
||||
Padding="20,16,20,12"
|
||||
CornerRadius="8"
|
||||
BorderThickness="1"
|
||||
BorderBrush="{DynamicResource CardStrokeColorDefaultBrush}"
|
||||
Background="{DynamicResource CardBackgroundFillColorDefaultBrush}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<StackPanel>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<StackPanel Grid.Column="0">
|
||||
<ui:TextBlock FontTypography="Caption"
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
Text="Läuft gerade" />
|
||||
<StackPanel Margin="0,4,0,0" Orientation="Horizontal">
|
||||
<ContentPresenter x:Name="NowKind"
|
||||
VerticalAlignment="Center"
|
||||
ContentTemplate="{StaticResource KindChip}"
|
||||
Visibility="Collapsed" />
|
||||
<ui:TextBlock x:Name="NowTitle"
|
||||
Margin="8,0,0,0"
|
||||
FontTypography="Subtitle"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
Text="Nichts auf Sendung" />
|
||||
<StackPanel VerticalAlignment="Center">
|
||||
<ui:TextBlock FontTypography="Caption"
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
Text="Läuft gerade" />
|
||||
<DockPanel Margin="0,4,0,0">
|
||||
<ContentPresenter x:Name="NowKind"
|
||||
Margin="0,0,8,0"
|
||||
VerticalAlignment="Center"
|
||||
ContentTemplate="{StaticResource KindChip}"
|
||||
Visibility="Collapsed" />
|
||||
<ui:TextBlock x:Name="NowTitle"
|
||||
FontTypography="Subtitle"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
Text="Nichts auf Sendung" />
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
<ProgressBar x:Name="NowProgress"
|
||||
Margin="0,12,0,0"
|
||||
AutomationProperties.Name="Fortschritt des aktuellen Elements"
|
||||
Maximum="1" />
|
||||
<ui:TextBlock x:Name="NowTime"
|
||||
Margin="0,6,0,0"
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
Text=" " />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Column="1" Margin="24,0,0,0" VerticalAlignment="Center">
|
||||
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
|
||||
<StackPanel Grid.Column="1" Margin="24,0,0,0" VerticalAlignment="Center" Orientation="Horizontal">
|
||||
<!-- Live microphone on the program channel; label and icon say whether it is on. -->
|
||||
<ui:Button x:Name="MicButton"
|
||||
MinWidth="120"
|
||||
Margin="0,0,20,0"
|
||||
Content="Mikro ein"
|
||||
Icon="{ui:SymbolIcon Mic24}"
|
||||
ToolTip="Schaltet das Mikrofon auf Sendung, auch ĂĽber laufende Musik."
|
||||
Click="OnMicToggle" />
|
||||
<ui:Button x:Name="EndNowButton"
|
||||
Content="Jetzt beenden"
|
||||
Icon="{ui:SymbolIcon Next24}"
|
||||
@@ -150,21 +150,105 @@
|
||||
IsEnabled="False"
|
||||
Click="OnPlayToggle" />
|
||||
</StackPanel>
|
||||
<StackPanel Margin="0,12,0,0" Orientation="Horizontal">
|
||||
<ui:SymbolIcon VerticalAlignment="Center" Symbol="Speaker224" />
|
||||
<Slider x:Name="VolumeSlider"
|
||||
Width="140"
|
||||
Margin="8,0,0,0"
|
||||
VerticalAlignment="Center"
|
||||
AutomationProperties.Name="Lautstärke"
|
||||
Minimum="0"
|
||||
Maximum="1"
|
||||
SmallChange="0.05"
|
||||
LargeChange="0.1"
|
||||
ValueChanged="OnVolumeChanged" />
|
||||
</Grid>
|
||||
|
||||
<ProgressBar x:Name="NowProgress"
|
||||
Margin="0,14,0,0"
|
||||
AutomationProperties.Name="Fortschritt des aktuellen Elements"
|
||||
Maximum="1" />
|
||||
<ui:TextBlock x:Name="NowTime"
|
||||
Margin="0,6,0,0"
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
Text=" " />
|
||||
|
||||
<Border Height="1" Margin="0,4,0,14" Background="{DynamicResource CardStrokeColorDefaultBrush}" />
|
||||
|
||||
<!-- Mixing desk: three groups of the same width, each a heading with its levels.
|
||||
The groups wrap below each other on a narrow window. -->
|
||||
<WrapPanel x:Name="MixPanel" Grid.IsSharedSizeScope="True">
|
||||
<WrapPanel.Resources>
|
||||
<Style TargetType="Slider" BasedOn="{StaticResource {x:Type Slider}}">
|
||||
<Setter Property="Margin" Value="12,0,0,0" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="Minimum" Value="0" />
|
||||
<Setter Property="Maximum" Value="1" />
|
||||
<Setter Property="SmallChange" Value="0.05" />
|
||||
<Setter Property="LargeChange" Value="0.1" />
|
||||
</Style>
|
||||
<Style x:Key="Group" TargetType="StackPanel">
|
||||
<Setter Property="Width" Value="208" />
|
||||
<Setter Property="Margin" Value="0,0,28,8" />
|
||||
</Style>
|
||||
<Style x:Key="Heading" TargetType="ui:TextBlock">
|
||||
<Setter Property="FontTypography" Value="Caption" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextFillColorSecondaryBrush}" />
|
||||
<Setter Property="Margin" Value="0,0,0,4" />
|
||||
</Style>
|
||||
</WrapPanel.Resources>
|
||||
|
||||
<StackPanel Style="{StaticResource Group}">
|
||||
<ui:TextBlock Style="{StaticResource Heading}" Text="Sendung (fĂĽr andere)" />
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="MixLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="32" />
|
||||
<RowDefinition Height="32" />
|
||||
</Grid.RowDefinitions>
|
||||
<ui:TextBlock VerticalAlignment="Center" Text="Musik" />
|
||||
<Slider x:Name="MusicForOthersSlider" Grid.Column="1"
|
||||
AutomationProperties.Name="Musik fĂĽr andere" ValueChanged="OnMixChanged" />
|
||||
<ui:TextBlock Grid.Row="1" VerticalAlignment="Center" Text="Mikrofon" />
|
||||
<Slider x:Name="MicrophoneForOthersSlider" Grid.Row="1" Grid.Column="1"
|
||||
AutomationProperties.Name="Mikrofon fĂĽr andere" ValueChanged="OnMixChanged" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<StackPanel Style="{StaticResource Group}">
|
||||
<ui:TextBlock Style="{StaticResource Heading}" Text="FĂĽr mich" />
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="MixLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="32" />
|
||||
<RowDefinition Height="32" />
|
||||
</Grid.RowDefinitions>
|
||||
<ui:TextBlock VerticalAlignment="Center" Text="Musik" />
|
||||
<Slider x:Name="MusicForMeSlider" Grid.Column="1"
|
||||
AutomationProperties.Name="Musik fĂĽr mich" ValueChanged="OnMixChanged" />
|
||||
<CheckBox x:Name="ListenToBroadcastBox"
|
||||
Grid.Row="1" Grid.ColumnSpan="2"
|
||||
MinWidth="0"
|
||||
Padding="8,0,0,0"
|
||||
VerticalAlignment="Center"
|
||||
Content="Sendung 1:1 hören"
|
||||
ToolTip="Du hörst genau das, was andere hören: gleiche Lautstärke von dir, Musik und allem anderen."
|
||||
Checked="OnMixChanged"
|
||||
Unchecked="OnMixChanged" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Style="{StaticResource Group}" Margin="0,0,0,8">
|
||||
<ui:TextBlock Style="{StaticResource Heading}" Text="Musik gesamt" />
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="MixLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="32" />
|
||||
</Grid.RowDefinitions>
|
||||
<ui:TextBlock VerticalAlignment="Center" Text="Lautstärke" />
|
||||
<Slider x:Name="VolumeSlider" Grid.Column="1"
|
||||
AutomationProperties.Name="Lautstärke der Musik gesamt" ValueChanged="OnVolumeChanged" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Song request (hot swap) on the left, actions for the selected timeline row on the right -->
|
||||
|
||||
@@ -29,9 +29,14 @@ public partial class SchedulePage : Page
|
||||
// Optimistic state: what the user just asked for, shown before the engine has caught up.
|
||||
private bool? _expectPlaying;
|
||||
|
||||
public SchedulePage(ScheduleController controller)
|
||||
private readonly Microphone _microphone;
|
||||
private readonly ProgramMixer _mixer;
|
||||
|
||||
public SchedulePage(ScheduleController controller, Microphone microphone, ProgramOutput output)
|
||||
{
|
||||
_controller = controller;
|
||||
_microphone = microphone;
|
||||
_mixer = output.Mixer;
|
||||
InitializeComponent();
|
||||
Timeline.ItemsSource = _rows;
|
||||
// Also refreshes the buttons: Finished can arrive just before the engine reports it stopped.
|
||||
@@ -51,7 +56,13 @@ public partial class SchedulePage : Page
|
||||
|
||||
_loading = true;
|
||||
VolumeSlider.Value = _controller.Volume;
|
||||
MusicForMeSlider.Value = _mixer.MusicForMe;
|
||||
MusicForOthersSlider.Value = _mixer.MusicForOthers;
|
||||
MicrophoneForOthersSlider.Value = _mixer.MicrophoneForOthers;
|
||||
ListenToBroadcastBox.IsChecked = _mixer.ListenToBroadcast;
|
||||
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
|
||||
_loading = false;
|
||||
ShowMicrophone(); // it stays on while the user visits other pages
|
||||
FillStartTimes();
|
||||
if (_controller.Plan.Count > 0)
|
||||
UnlimitedBox.IsChecked = _controller.IsUnlimited;
|
||||
@@ -162,6 +173,49 @@ public partial class SchedulePage : Page
|
||||
Timeline.SelectedIndex = row.Index + offset;
|
||||
});
|
||||
|
||||
private void OnMixChanged(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_loading) return;
|
||||
_mixer.MusicForMe = (float)MusicForMeSlider.Value;
|
||||
_mixer.MusicForOthers = (float)MusicForOthersSlider.Value;
|
||||
_mixer.MicrophoneForOthers = (float)MicrophoneForOthersSlider.Value;
|
||||
_mixer.ListenToBroadcast = ListenToBroadcastBox.IsChecked == true;
|
||||
// While the monitor copies the broadcast, its own music level has no effect.
|
||||
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
|
||||
}
|
||||
|
||||
private async void OnMicToggle(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var turnOn = !_microphone.IsOn;
|
||||
MicButton.IsEnabled = false;
|
||||
try
|
||||
{
|
||||
// Opening the devices can take a moment, so it runs off the UI thread.
|
||||
await Task.Run(() =>
|
||||
{
|
||||
if (turnOn) _microphone.TurnOn();
|
||||
else _microphone.TurnOff();
|
||||
});
|
||||
Message.IsOpen = false;
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
ShowMessage(InfoBarSeverity.Error, "Mikrofon nicht verfĂĽgbar", ex.Message);
|
||||
}
|
||||
MicButton.IsEnabled = true;
|
||||
ShowMicrophone();
|
||||
}
|
||||
|
||||
private void ShowMicrophone()
|
||||
{
|
||||
var on = _microphone.IsOn;
|
||||
// The label names the action; the red button shows that the microphone is live.
|
||||
MicButton.Content = on ? "Mikro aus" : "Mikro ein";
|
||||
MicButton.Icon = new SymbolIcon(on ? SymbolRegular.MicOff24 : SymbolRegular.Mic24);
|
||||
MicButton.Appearance = on ? ControlAppearance.Danger : ControlAppearance.Secondary;
|
||||
System.Windows.Automation.AutomationProperties.SetName(MicButton, on ? "Mikrofon ausschalten, es ist auf Sendung" : "Mikrofon einschalten");
|
||||
}
|
||||
|
||||
private void OnEndNow(object sender, RoutedEventArgs e)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -90,6 +90,34 @@
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Audio devices -->
|
||||
<Border Style="{StaticResource Card}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="220" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<ui:TextBlock Grid.ColumnSpan="2" FontTypography="BodyStrong" Text="Audio-Ausgabe" />
|
||||
<Label Grid.Row="1" Margin="0,12,0,0" VerticalAlignment="Center"
|
||||
Content="Sendung (fĂĽr andere)" Target="{Binding ElementName=BroadcastDeviceBox}" />
|
||||
<ComboBox x:Name="BroadcastDeviceBox" Grid.Row="1" Grid.Column="1" Margin="0,12,0,0"
|
||||
AutomationProperties.Name="Ausgabegerät für die Sendung" />
|
||||
<Label Grid.Row="2" Margin="0,8,0,0" VerticalAlignment="Center"
|
||||
Content="Für mich (Kopfhörer)" Target="{Binding ElementName=MonitorDeviceBox}" />
|
||||
<ComboBox x:Name="MonitorDeviceBox" Grid.Row="2" Grid.Column="1" Margin="0,8,0,0"
|
||||
AutomationProperties.Name="Ausgabegerät für mich" />
|
||||
<ui:TextBlock Grid.Row="3" Grid.ColumnSpan="2" Margin="0,12,0,0" TextWrapping="Wrap"
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
Text="Getrennte Lautstärken für dich und für andere brauchen zwei verschiedene Geräte. Mit nur einem Gerät hörst du deinen eigenen Mix." />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Minutes per hour -->
|
||||
<Border Style="{StaticResource Card}">
|
||||
<Grid>
|
||||
|
||||
@@ -20,8 +20,18 @@ public partial class SettingsPage : Page
|
||||
// Loaded fires on every navigation to the page, so unsaved edits from an earlier visit are dropped.
|
||||
private void OnLoaded(object sender, RoutedEventArgs e) => Show(_store.Current);
|
||||
|
||||
// First entry of each list: the choice that names no device.
|
||||
private const string DefaultDevice = "Windows-Standardgerät";
|
||||
private const string NoDevice = "Kein eigenes Gerät";
|
||||
|
||||
private void Show(AppSettings settings)
|
||||
{
|
||||
// Read again on every visit, so a headset plugged in meanwhile shows up.
|
||||
var devices = ProgramOutput.DeviceNames().ToList();
|
||||
BroadcastDeviceBox.ItemsSource = devices.Prepend(DefaultDevice).ToList();
|
||||
MonitorDeviceBox.ItemsSource = devices.Prepend(NoDevice).ToList();
|
||||
BroadcastDeviceBox.SelectedIndex = devices.IndexOf(settings.BroadcastDevice ?? "") + 1;
|
||||
MonitorDeviceBox.SelectedIndex = devices.IndexOf(settings.MonitorDevice ?? "") + 1;
|
||||
NewsAlertSwitch.IsChecked = settings.NewsAlert;
|
||||
NewsSecondsBox.Value = settings.NewsAlertSeconds;
|
||||
NewsSoundBox.IsChecked = settings.NewsAlertSound;
|
||||
@@ -47,6 +57,8 @@ public partial class SettingsPage : Page
|
||||
NewsMinutesPerHour = (int)(NewsMinutesBox.Value ?? Defaults.NewsMinutesPerHour),
|
||||
ModeratorMinutesPerHour = (int)(ModeratorMinutesBox.Value ?? Defaults.ModeratorMinutesPerHour),
|
||||
AdMinutesPerHour = (int)(AdMinutesBox.Value ?? Defaults.AdMinutesPerHour),
|
||||
BroadcastDevice = BroadcastDeviceBox.SelectedIndex > 0 ? (string)BroadcastDeviceBox.SelectedItem : null,
|
||||
MonitorDevice = MonitorDeviceBox.SelectedIndex > 0 ? (string)MonitorDeviceBox.SelectedItem : null,
|
||||
};
|
||||
|
||||
private void OnSave(object sender, RoutedEventArgs e)
|
||||
@@ -63,6 +75,10 @@ public partial class SettingsPage : Page
|
||||
_store.Save(settings);
|
||||
ShowMessage(InfoBarSeverity.Success, "Gespeichert", "Minuten pro Stunde gelten für den nächsten Plan.");
|
||||
}
|
||||
catch (NAudio.MmException)
|
||||
{
|
||||
ShowMessage(InfoBarSeverity.Error, "Nicht gespeichert", "Ein gewähltes Audiogerät konnte nicht geöffnet werden. Die bisherigen Geräte bleiben aktiv.");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
ShowMessage(InfoBarSeverity.Error, "Nicht gespeichert", ex.Message);
|
||||
|
||||
@@ -26,9 +26,9 @@ public sealed class MusicPlayerTests : IDisposable
|
||||
}
|
||||
|
||||
// Writes a short, quiet sine tone as 16-bit mono PCM.
|
||||
private string CreateWav(TimeSpan length)
|
||||
private string CreateWav(TimeSpan length, string name = "tone.wav")
|
||||
{
|
||||
var path = Path.Combine(_directory, "tone.wav");
|
||||
var path = Path.Combine(_directory, name);
|
||||
var format = new WaveFormat(44100, 16, 1);
|
||||
using var writer = new WaveFileWriter(path, format);
|
||||
var samples = (int)(format.SampleRate * length.TotalSeconds);
|
||||
@@ -37,6 +37,62 @@ public sealed class MusicPlayerTests : IDisposable
|
||||
return path;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProgramOutput_ConvertsInputsToItsFormat()
|
||||
{
|
||||
var mono = new NAudio.Wave.SampleProviders.SignalGenerator(22050, 1);
|
||||
|
||||
var converted = ProgramOutput.ToProgramFormat(mono);
|
||||
|
||||
Assert.Equal(44100, converted.WaveFormat.SampleRate);
|
||||
Assert.Equal(2, converted.WaveFormat.Channels);
|
||||
Assert.Same(ProgramOutput.Instance, ProgramOutput.Instance);
|
||||
Assert.Throws<NotSupportedException>(() => ProgramOutput.ToProgramFormat(new NAudio.Wave.SampleProviders.SignalGenerator(44100, 6)));
|
||||
}
|
||||
|
||||
[AudioDeviceFact]
|
||||
public void PauseAndResume_KeepThePosition()
|
||||
{
|
||||
var player = MusicPlayer.Instance;
|
||||
player.Play(CreateWav(TimeSpan.FromSeconds(3)));
|
||||
Thread.Sleep(400);
|
||||
|
||||
player.Pause();
|
||||
Assert.False(player.IsPlaying);
|
||||
var paused = player.Position;
|
||||
Thread.Sleep(300);
|
||||
Assert.Equal(paused, player.Position);
|
||||
|
||||
player.Resume();
|
||||
Assert.True(player.IsPlaying);
|
||||
Thread.Sleep(400);
|
||||
Assert.True(player.Position > paused);
|
||||
}
|
||||
|
||||
[AudioDeviceFact]
|
||||
public void Play_TwoTracksInARow_RaisesTrackFinishedOnlyForTheSecond()
|
||||
{
|
||||
var player = MusicPlayer.Instance;
|
||||
var finished = 0;
|
||||
using var done = new ManualResetEventSlim();
|
||||
EventHandler handler = (_, _) => { Interlocked.Increment(ref finished); done.Set(); };
|
||||
player.TrackFinished += handler;
|
||||
try
|
||||
{
|
||||
player.Play(CreateWav(TimeSpan.FromSeconds(2)));
|
||||
Thread.Sleep(200);
|
||||
player.Play(CreateWav(TimeSpan.FromSeconds(0.5), "second.wav"));
|
||||
|
||||
Assert.True(done.Wait(TimeSpan.FromSeconds(5)));
|
||||
Thread.Sleep(300);
|
||||
Assert.Equal(1, finished);
|
||||
}
|
||||
finally
|
||||
{
|
||||
player.TrackFinished -= handler;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Instance_ReturnsSameObjectOnRepeatedAccess()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
using NAudio.Wave;
|
||||
using Radiosender.Services;
|
||||
|
||||
namespace Radiosender.Tests;
|
||||
|
||||
public class ProgramMixerTests
|
||||
{
|
||||
/// <summary>Delivers the same sample value for a given number of samples, then ends.</summary>
|
||||
private sealed class Constant(float value, int samples = int.MaxValue) : ISampleProvider
|
||||
{
|
||||
private int _left = samples;
|
||||
|
||||
public WaveFormat WaveFormat => ProgramOutput.Format;
|
||||
|
||||
public int Read(Span<float> buffer)
|
||||
{
|
||||
var count = Math.Min(buffer.Length, _left);
|
||||
buffer[..count].Fill(value);
|
||||
_left -= count;
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
private static (float Broadcast, float Monitor) MixOnce(ProgramMixer mixer)
|
||||
{
|
||||
Span<float> broadcast = stackalloc float[8];
|
||||
Span<float> monitor = stackalloc float[8];
|
||||
mixer.Mix(broadcast, monitor);
|
||||
return (broadcast[0], monitor[0]);
|
||||
}
|
||||
|
||||
private static ProgramMixer WithMusicAndMicrophone()
|
||||
{
|
||||
var mixer = new ProgramMixer { ListenToBroadcast = false };
|
||||
mixer.Add(new Constant(0.4f), AudioSource.Music);
|
||||
mixer.Add(new Constant(0.2f), AudioSource.Microphone);
|
||||
return mixer;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mix_AppliesEachLevelToItsOwnMix()
|
||||
{
|
||||
var mixer = WithMusicAndMicrophone();
|
||||
mixer.MusicForOthers = 0.5f;
|
||||
mixer.MicrophoneForOthers = 1f;
|
||||
mixer.MusicForMe = 0.25f;
|
||||
|
||||
var (broadcast, monitor) = MixOnce(mixer);
|
||||
|
||||
Assert.Equal(0.4f * 0.5f + 0.2f, broadcast, 5);
|
||||
Assert.Equal(0.4f * 0.25f, monitor, 5); // the monitor never carries the microphone
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mix_ListeningToTheBroadcastCopiesItExactly()
|
||||
{
|
||||
var mixer = WithMusicAndMicrophone();
|
||||
mixer.MusicForOthers = 0.5f;
|
||||
mixer.MusicForMe = 0f;
|
||||
mixer.ListenToBroadcast = true;
|
||||
|
||||
var (broadcast, monitor) = MixOnce(mixer);
|
||||
|
||||
Assert.Equal(0.4f, broadcast, 5);
|
||||
Assert.Equal(broadcast, monitor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mix_LimitsTheSumToFullScale()
|
||||
{
|
||||
var mixer = new ProgramMixer();
|
||||
mixer.Add(new Constant(0.8f), AudioSource.Music);
|
||||
mixer.Add(new Constant(0.8f), AudioSource.Microphone);
|
||||
|
||||
Assert.Equal(1f, MixOnce(mixer).Broadcast);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mix_DropsAnInputThatEndedAndReportsIt()
|
||||
{
|
||||
var mixer = new ProgramMixer();
|
||||
var track = new Constant(0.5f, samples: 4);
|
||||
ISampleProvider? ended = null;
|
||||
mixer.InputEnded += (_, input) => ended = input;
|
||||
mixer.Add(track, AudioSource.Music);
|
||||
|
||||
Span<float> broadcast = stackalloc float[8];
|
||||
Span<float> monitor = stackalloc float[8];
|
||||
mixer.Mix(broadcast, monitor);
|
||||
|
||||
Assert.Same(track, ended);
|
||||
Assert.Equal(0.5f, broadcast[3]);
|
||||
Assert.Equal(0f, broadcast[4]); // silence after the end of the track
|
||||
Assert.Equal(0f, MixOnce(mixer).Broadcast);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Remove_TakesTheInputOffBothMixes()
|
||||
{
|
||||
var mixer = new ProgramMixer();
|
||||
var track = new Constant(0.5f);
|
||||
mixer.Add(track, AudioSource.Music);
|
||||
|
||||
mixer.Remove(track);
|
||||
|
||||
Assert.Equal((0f, 0f), MixOnce(mixer));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Levels_OutOfRange_Throw()
|
||||
{
|
||||
var mixer = new ProgramMixer();
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => mixer.MusicForMe = 1.1f);
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => mixer.MicrophoneForOthers = -0.1f);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user