Repository navigation
Expand file tree
/
Copy pathSampletap.cs
More file actions
47 lines (41 loc) · 1.73 KB
/
Copy pathSampletap.cs
File metadata and controls
47 lines (41 loc) · 1.73 KB
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
using System;
using NAudio.Wave;
namespace MusicVisualizer
{
public class SampleTap : ISampleProvider
{
private readonly ISampleProvider _source;
private readonly int _fftSize;
private readonly Action<double[]> _callback;
private readonly double[] _ring; // кольцевой буфер
private int _pos; // текущая позция в буфере
public NAudio.Wave.WaveFormat WaveFormat => _source.WaveFormat;
public SampleTap(ISampleProvider source, int fftSize, Action<double[]> callback)
{
_source = source;
_fftSize = fftSize;
_callback = callback;
_ring = new double[fftSize];
}
// преводит стерео звук в моно, накапливает сэмплов в кольцевом буфере и отправка на fft анализ
public int Read(float[] buffer, int offset, int count)
{
int read = _source.Read(buffer, offset, count);
int channels = _source.WaveFormat.Channels; // через _source напрямую
for (int i = 0; i < read; i += channels)
{
double mono = 0;
for (int c = 0; c < channels; c++)
mono += buffer[offset + i + c];
_ring[_pos++] = mono / channels;
if (_pos >= _fftSize)
{
_pos = 0;
var snap = (double[])_ring.Clone();
System.Threading.ThreadPool.QueueUserWorkItem(_ => _callback(snap));//фоновый поток, не блокирующий аудиопоток
}
}
return read;
}
}
}