基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-12 97df0fb5ed49e37d1c8e0e62057bb72ba5c9eb6a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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<string, string>
                {
                    ["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<string, string> { ["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<string, string> { ["exception"] = e.Exception.GetType().Name, ["message"] = e.Exception.Message });
    }
 
    private static float[] DecodeToMonoSamples(ReadOnlySpan<byte> 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<byte> 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<byte> sample)
    {
        var value = sample[0] | (sample[1] << 8) | (sample[2] << 16);
        if ((value & 0x800000) != 0)
        {
            value |= unchecked((int)0xFF000000);
        }
 
        return value;
    }
}