using System;
using NAudio.Utils;
// ReSharper disable once CheckNamespace
namespace NAudio.Wave
{
///
/// Provides a buffered store of samples
/// Read method will return queued samples or fill buffer with zeroes
/// Now backed by a circular buffer
///
public class BufferedWaveProvider : IWaveProvider
{
private CircularBuffer circularBuffer;
private readonly WaveFormat waveFormat;
///
/// Creates a new buffered WaveProvider
///
/// WaveFormat
public BufferedWaveProvider(WaveFormat waveFormat)
{
this.waveFormat = waveFormat;
BufferLength = waveFormat.AverageBytesPerSecond * 5;
ReadFully = true;
}
///
/// If true, always read the amount of data requested, padding with zeroes if necessary
/// By default is set to true
///
public bool ReadFully { get; set; }
///
/// Buffer length in bytes
///
public int BufferLength { get; set; }
///
/// Buffer duration
///
public TimeSpan BufferDuration
{
get
{
return TimeSpan.FromSeconds((double)BufferLength / WaveFormat.AverageBytesPerSecond);
}
set
{
BufferLength = (int)(value.TotalSeconds * WaveFormat.AverageBytesPerSecond);
}
}
///
/// If true, when the buffer is full, start throwing away data
/// if false, AddSamples will throw an exception when buffer is full
///
public bool DiscardOnBufferOverflow { get; set; }
///
/// The number of buffered bytes
///
public int BufferedBytes
{
get
{
return circularBuffer == null ? 0 : circularBuffer.Count;
}
}
///
/// Buffered Duration
///
public TimeSpan BufferedDuration
{
get { return TimeSpan.FromSeconds((double)BufferedBytes / WaveFormat.AverageBytesPerSecond); }
}
///
/// Gets the WaveFormat
///
public WaveFormat WaveFormat
{
get { return waveFormat; }
}
///
/// Adds samples. Takes a copy of buffer, so that buffer can be reused if necessary
///
public void AddSamples(byte[] buffer, int offset, int count)
{
// create buffer here to allow user to customise buffer length
if (circularBuffer == null)
{
circularBuffer = new CircularBuffer(BufferLength);
}
var written = circularBuffer.Write(buffer, offset, count);
if (written < count && !DiscardOnBufferOverflow)
{
throw new InvalidOperationException("Buffer full");
}
}
///
/// Reads from this WaveProvider
/// Will always return count bytes, since we will zero-fill the buffer if not enough available
///
public int Read(byte[] buffer, int offset, int count)
{
int read = 0;
if (circularBuffer != null) // not yet created
{
read = circularBuffer.Read(buffer, offset, count);
}
if (ReadFully && read < count)
{
// zero the end of the buffer
Array.Clear(buffer, offset + read, count - read);
read = count;
}
return read;
}
///
/// Discards all audio from the buffer
///
public void ClearBuffer()
{
if (circularBuffer != null)
{
circularBuffer.Reset();
}
}
}
}