using System;
using System.Linq;
using NAudio.Dsp;
namespace NAudio.Wave.SampleProviders
{
///
/// ADSR sample provider allowing you to specify attack, decay, sustain and release values
///
public class AdsrSampleProvider : ISampleProvider
{
private readonly ISampleProvider source;
private readonly EnvelopeGenerator adsr;
private float attackSeconds;
private float releaseSeconds;
///
/// Creates a new AdsrSampleProvider with default values
///
public AdsrSampleProvider(ISampleProvider source)
{
if (source.WaveFormat.Channels > 1) throw new ArgumentException("Currently only supports mono inputs");
this.source = source;
adsr = new EnvelopeGenerator();
AttackSeconds = 0.01f;
adsr.SustainLevel = 1.0f;
adsr.DecayRate = 0.0f * WaveFormat.SampleRate;
ReleaseSeconds = 0.3f;
adsr.Gate(true);
}
///
/// Attack time in seconds
///
public float AttackSeconds
{
get
{
return attackSeconds;
}
set
{
attackSeconds = value;
adsr.AttackRate = attackSeconds * WaveFormat.SampleRate;
}
}
///
/// Release time in seconds
///
public float ReleaseSeconds
{
get
{
return releaseSeconds;
}
set
{
releaseSeconds = value;
adsr.ReleaseRate = releaseSeconds * WaveFormat.SampleRate;
}
}
///
/// Reads audio from this sample provider
///
public int Read(float[] buffer, int offset, int count)
{
if (adsr.State == EnvelopeGenerator.EnvelopeState.Idle) return 0; // we've finished
var samples = source.Read(buffer, offset, count);
for (int n = 0; n < samples; n++)
{
buffer[offset++] *= adsr.Process();
}
return samples;
}
///
/// Enters the Release phase
///
public void Stop()
{
adsr.Gate(false);
}
///
/// The output WaveFormat
///
public WaveFormat WaveFormat { get { return source.WaveFormat; } }
}
}