using Microsoft.Extensions.Hosting; using Moli.Desktop.Diagnostics; using Moli.Desktop.Runtime; using NAudio.Wave; namespace Moli.Desktop.Audio; public sealed class WasapiLoopbackAudioSpectrumService : BackgroundService { private static readonly TimeSpan PublishInterval = TimeSpan.FromMilliseconds(33); private readonly IDiagnosticsService _diagnostics; private readonly IRuntimeEventBus _events; private WasapiLoopbackCapture? _capture; private AudioSpectrumAnalyzer? _analyzer; public WasapiLoopbackAudioSpectrumService(IDiagnosticsService diagnostics, IRuntimeEventBus events) { _diagnostics = diagnostics; _events = events; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { _capture = new WasapiLoopbackCapture(); _analyzer = new AudioSpectrumAnalyzer(_capture.WaveFormat.SampleRate); _capture.DataAvailable += OnDataAvailable; _capture.RecordingStopped += OnRecordingStopped; _capture.StartRecording(); _diagnostics.Record( DiagnosticSeverity.Info, "AudioLoopbackStarted", "WASAPI loopback audio capture started.", new Dictionary { ["sampleRate"] = _capture.WaveFormat.SampleRate.ToString(), ["channels"] = _capture.WaveFormat.Channels.ToString() }); using var timer = new PeriodicTimer(PublishInterval); while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)) { if (_analyzer.TryCreateFrame(out var frame)) { await _events.PublishAsync(new RuntimeEvent { Name = "audio.spectrum", Payload = frame }, stoppingToken).ConfigureAwait(false); } } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { } catch (Exception ex) { _diagnostics.Record( DiagnosticSeverity.Warning, "AudioLoopbackFailed", "WASAPI loopback audio capture failed.", new Dictionary { ["exception"] = ex.GetType().Name, ["message"] = ex.Message }); } } public override async Task StopAsync(CancellationToken cancellationToken) { if (_capture is not null) { _capture.DataAvailable -= OnDataAvailable; _capture.RecordingStopped -= OnRecordingStopped; _capture.StopRecording(); _capture.Dispose(); _capture = null; } await base.StopAsync(cancellationToken).ConfigureAwait(false); } private void OnDataAvailable(object? sender, WaveInEventArgs e) { if (_capture is null || _analyzer is null) { return; } var samples = DecodeToMonoSamples(e.Buffer.AsSpan(0, e.BytesRecorded), _capture.WaveFormat); _analyzer.AddSamples(samples); } private void OnRecordingStopped(object? sender, StoppedEventArgs e) { if (e.Exception is null) { return; } _diagnostics.Record( DiagnosticSeverity.Warning, "AudioLoopbackStopped", "WASAPI loopback audio capture stopped unexpectedly.", new Dictionary { ["exception"] = e.Exception.GetType().Name, ["message"] = e.Exception.Message }); } private static float[] DecodeToMonoSamples(ReadOnlySpan buffer, WaveFormat format) { var bytesPerSample = format.BitsPerSample / 8; if (bytesPerSample <= 0 || format.Channels <= 0) { return []; } var frameSize = bytesPerSample * format.Channels; var frameCount = buffer.Length / frameSize; var samples = new float[frameCount]; for (var frame = 0; frame < frameCount; frame++) { var frameOffset = frame * frameSize; var sum = 0f; for (var channel = 0; channel < format.Channels; channel++) { var offset = frameOffset + channel * bytesPerSample; sum += DecodeSample(buffer[offset..], format); } samples[frame] = sum / format.Channels; } return samples; } private static float DecodeSample(ReadOnlySpan sample, WaveFormat format) { if (format.Encoding == WaveFormatEncoding.IeeeFloat && format.BitsPerSample == 32) { return BitConverter.ToSingle(sample[..4]); } return format.BitsPerSample switch { 16 => BitConverter.ToInt16(sample[..2]) / 32768f, 24 => Decode24BitSample(sample[..3]) / 8388608f, 32 => BitConverter.ToInt32(sample[..4]) / 2147483648f, _ => 0f }; } private static int Decode24BitSample(ReadOnlySpan sample) { var value = sample[0] | (sample[1] << 8) | (sample[2] << 16); if ((value & 0x800000) != 0) { value |= unchecked((int)0xFF000000); } return value; } }