10internal sealed class VariableSpeedSampleProvider : ISampleProvider
12 private readonly ISampleProvider _source;
13 private readonly
int _channels;
14 private readonly
float[] _currentFrame;
15 private readonly
float[] _nextFrame;
16 private readonly
object _sync =
new();
18 private bool _initialized;
19 private bool _hasCurrent;
20 private bool _hasNext;
21 private double _phase;
22 private float _playbackSpeed = 1.0f;
30 public VariableSpeedSampleProvider(ISampleProvider source)
32 _source = source ??
throw new ArgumentNullException(nameof(source));
33 _channels = source.WaveFormat.Channels;
36 throw new ArgumentException(
"Source must expose at least one audio channel.", nameof(source));
38 _currentFrame =
new float[_channels];
39 _nextFrame =
new float[_channels];
45 public WaveFormat WaveFormat => _source.WaveFormat;
54 public float PlaybackSpeed
56 get => Volatile.Read(ref _playbackSpeed);
57 set => Volatile.Write(
59 Math.Clamp(value, AudioResource.MinimumPlaybackSpeed, AudioResource.MaximumPlaybackSpeed));
70 public int Read(
float[] buffer,
int offset,
int count)
82 var frameCapacity = count / _channels;
83 var framesWritten = 0;
85 while (framesWritten < frameCapacity && _hasCurrent)
87 var destination = offset + (framesWritten * _channels);
88 var phase = (float)_phase;
90 for (var channel = 0; channel < _channels; channel++)
92 var next = _hasNext ? _nextFrame[channel] : _currentFrame[channel];
93 buffer[destination + channel] = _currentFrame[channel] + ((next - _currentFrame[channel]) * phase);
97 _phase += PlaybackSpeed;
99 while (_phase >= 1.0 && _hasCurrent)
106 return framesWritten * _channels;
114 public void Reset(Action? reposition =
null)
118 reposition?.Invoke();
119 _initialized =
false;
126 private void EnsureInitialized()
131 _hasCurrent = ReadFrame(_currentFrame);
132 _hasNext = _hasCurrent && ReadFrame(_nextFrame);
137 private void AdvanceFrame()
145 Array.Copy(_nextFrame, _currentFrame, _channels);
147 _hasNext = ReadFrame(_nextFrame);
150 private bool ReadFrame(
float[] frame)
154 while (read < _channels)
156 var count = _source.Read(frame, read, _channels - read);