Audio and MIDI library for .NET
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

113 lines
3.5 KiB

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using NAudio.Wave;
using NAudio.Utils;
namespace NAudio.Wave
{
/// <summary>
/// Provides a buffered store of samples
/// Read method will return queued samples or fill buffer with zeroes
/// Now backed by a circular buffer
/// </summary>
public class BufferedWaveProvider : IWaveProvider
{
private CircularBuffer buffer;
private WaveFormat waveFormat;
/// <summary>
/// Creates a new buffered WaveProvider
/// </summary>
/// <param name="waveFormat">WaveFormat</param>
public BufferedWaveProvider(WaveFormat waveFormat)
{
this.waveFormat = waveFormat;
this.BufferLength = waveFormat.AverageBytesPerSecond * 5;
}
/// <summary>
/// Buffer length in bytes
/// </summary>
public int BufferLength { get; set; }
/// <summary>
/// Buffer duration
/// </summary>
public TimeSpan BufferDuration
{
get
{
return TimeSpan.FromSeconds((double)BufferLength / WaveFormat.AverageBytesPerSecond);
}
set
{
BufferLength = (int)(value.TotalSeconds * WaveFormat.AverageBytesPerSecond);
}
}
/// <summary>
/// If true, when we get too many buffers, start throwing away the oldest ones,
/// if false, throws an exception whene queue is full
/// </summary>
public bool DiscardOnBufferOverflow { get; set; }
/// <summary>
/// The number of buffered bytes
/// </summary>
public int BufferedBytes
{
get { if (buffer == null) return 0; return buffer.Count; }
}
/// <summary>
/// Buffered Duration
/// </summary>
public TimeSpan BufferedDuration
{
get { return TimeSpan.FromSeconds((double)BufferedBytes / WaveFormat.AverageBytesPerSecond); }
}
/// <summary>
/// Gets the WaveFormat
/// </summary>
public WaveFormat WaveFormat
{
get { return waveFormat; }
}
/// <summary>
/// Adds samples. Takes a copy of buffer, so that buffer can be reused if necessary
/// </summary>
public void AddSamples(byte[] buffer, int offset, int count)
{
// create buffer here to allow user to customise buffer length
if (this.buffer == null)
{
this.buffer = new CircularBuffer(this.BufferLength);
}
int written = this.buffer.Write(buffer, offset, count);
if (written < count)
{
throw new InvalidOperationException("Buffer full");
}
}
/// <summary>
/// Reads from this WaveProvider
/// Will always return count bytes, since we will zero-fill the buffer if not enough available
/// </summary>
public int Read(byte[] buffer, int offset, int count)
{
int read = this.buffer.Read(buffer, offset, count);
if (read < count)
{
// zero the end of the buffer
Array.Clear(buffer, offset + read, count - read);
}
return count;
}
}
}