Skip to content

Commit 18c0278

Browse files
committed
- Refactored OnDataAvailable:
explicit mono conversion & frame-based processing - Фnd optimized SpectrumAnalyzer.cs code with null checks , removing limitations imposed by Constants.MinFreq and Constants.MaxFreq. implement here also more accurate and robust bin calculation in ProcessScale, ensuring correct mapping of frequencies to spectrum bins for logarithmic and perceptual scales.
1 parent 7793786 commit 18c0278

File tree

3 files changed

+196
-79
lines changed

3 files changed

+196
-79
lines changed

SpectrumNet/AudioCaptureManager.cs

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,6 @@ void TryStopCapture(string errorMsg)
116116
}
117117
}
118118

119-
// Убрано условие if(IsRecording) — переинициализация выполняется всегда
120119
public async Task ReinitializeCaptureAsync()
121120
{
122121
try
@@ -136,7 +135,6 @@ public async Task ReinitializeCaptureAsync()
136135

137136
_lastDeviceId = device.ID;
138137

139-
// Переинициализация UI и компонентов захвата выполняется всегда
140138
DisposeCaptureState(_state);
141139
_state = null;
142140

@@ -337,17 +335,41 @@ private void OnDataAvailable(object? sender, WaveInEventArgs e)
337335
if (e.BytesRecorded <= 0 || _state?.Analyzer == null)
338336
return;
339337

340-
var samples = new float[e.BytesRecorded / 4];
338+
var waveFormat = _state.Capture.WaveFormat;
339+
int channels = waveFormat.Channels; // Usually 2 for stereo
340+
int totalFloatSamples = e.BytesRecorded / 4; // Total float values in e.Buffer
341+
int frameCount = totalFloatSamples / channels; // Number of frames (one value per channel in each frame)
342+
343+
// Array for "mono" samples
344+
float[] monoSamples = new float[frameCount];
345+
341346
try
342347
{
343-
Buffer.BlockCopy(e.Buffer, 0, samples, 0, e.BytesRecorded);
348+
// Iterate over all frames (each contains [channels] float values)
349+
for (int frame = 0; frame < frameCount; frame++)
350+
{
351+
float sum = 0f;
352+
// Sum all channels (usually 2: L+R) and divide by their number,
353+
// to get the "average" (mono).
354+
for (int ch = 0; ch < channels; ch++)
355+
{
356+
// Byte offset within e.Buffer
357+
int sampleIndex = (frame * channels + ch) * 4;
358+
float sampleValue = BitConverter.ToSingle(e.Buffer, sampleIndex);
359+
sum += sampleValue;
360+
}
361+
monoSamples[frame] = sum / channels;
362+
}
344363
}
345364
catch (Exception ex)
346365
{
347366
SmartLogger.Log(LogLevel.Error, LogPrefix, $"Error processing audio data: {ex}");
348367
return;
349368
}
350-
_ = _state.Analyzer.AddSamplesAsync(samples, _state.Capture.WaveFormat.SampleRate);
369+
370+
// Now monoSamples contains 1 channel (sum of left and right).
371+
// Pass the MONO array to the analyzer.
372+
_ = _state.Analyzer.AddSamplesAsync(monoSamples, waveFormat.SampleRate);
351373
}
352374

353375
private async Task MonitorCaptureAsync(CancellationToken token)

SpectrumNet/SharedConstants.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@ public static class SharedConstants
88
// Здесь задаются значения по умолчанию для уровня децибелов и коэффициента усиления.
99
public const float DefaultMinDb = -130f; // Минимальный уровень. (-80)
1010
public const float DefaultMaxDb = -20f; // Максимальный уровень (0 дБ).
11-
public const float DefaultAmplificationFactor = 5.0f; // 1f
11+
public const float DefaultAmplificationFactor = 2.0f; // 1f
1212
}
1313
}

0 commit comments

Comments
 (0)