using System; namespace NAudio.Wave.SampleProviders { /// /// Simple SampleProvider that passes through audio unchanged and raises /// an event every n samples with the maximum sample value from the period /// for metering purposes /// public class MeteringSampleProvider : ISampleProvider { private readonly ISampleProvider source; private readonly float[] maxSamples; private int sampleCount; private readonly int channels; private readonly StreamVolumeEventArgs args; /// /// Number of Samples per notification /// public int SamplesPerNotification { get; set; } /// /// Raised periodically to inform the user of the max volume /// public event EventHandler StreamVolume; /// /// Initialises a new instance of MeteringSampleProvider that raises 10 stream volume /// events per second /// /// Source sample provider public MeteringSampleProvider(ISampleProvider source) : this(source, source.WaveFormat.SampleRate / 10) { } /// /// Initialises a new instance of MeteringSampleProvider /// /// source sampler provider /// Number of samples between notifications public MeteringSampleProvider(ISampleProvider source, int samplesPerNotification) { this.source = source; channels = source.WaveFormat.Channels; maxSamples = new float[channels]; SamplesPerNotification = samplesPerNotification; args = new StreamVolumeEventArgs() { MaxSampleValues = maxSamples }; // create objects up front giving GC little to do } /// /// The WaveFormat of this sample provider /// public WaveFormat WaveFormat => source.WaveFormat; /// /// Reads samples from this Sample Provider /// /// Sample buffer /// Offset into sample buffer /// Number of samples required /// Number of samples read public int Read(float[] buffer, int offset, int count) { int samplesRead = source.Read(buffer, offset, count); // only bother if there is an event listener if (StreamVolume != null) { for (int index = 0; index < samplesRead; index += channels) { for (int channel = 0; channel < channels; channel++) { float sampleValue = Math.Abs(buffer[offset + index + channel]); maxSamples[channel] = Math.Max(maxSamples[channel], sampleValue); } sampleCount++; if (sampleCount >= SamplesPerNotification) { StreamVolume(this, args); sampleCount = 0; // n.b. we avoid creating new instances of anything here Array.Clear(maxSamples, 0, channels); } } } return samplesRead; } } /// /// Event args for aggregated stream volume /// public class StreamVolumeEventArgs : EventArgs { /// /// Max sample values array (one for each channel) /// public float[] MaxSampleValues { get; set; } } }