用於播放流式聲音
public class SoundPlayer : IDisposable
{
私有成員#region 私有成員
private const int MaxLatencyMs = 300;
private const int NumberRecordNotifications = 4;
private readonly CircularBuffer circularBuffer;
private readonly int m_BufferBytes;
private readonly bool m_OwnsDevice;
private readonly int notifySize;
private readonly BufferPositionNotify[] positionNotify;
private bool isRunning;
private SecondaryBuffer m_Buffer;
private Device m_Device;
private int nextWriteOffset;
private AutoResetEvent notificationEvent;
private Notify notify;
private Thread notifyThread;
#endregion
構造函數#region 構造函數
public SoundPlayer(Control owner, WaveFormat format)
: this(owner, null, format)
{
}
public SoundPlayer(Control owner, Device device, WaveFormat format)
{
positionNotify = new BufferPositionNotify[5];
notificationEvent = null;
notify = null;
notifyThread = null;
notifySize = 0;
m_Device = device;
if (m_Device == null)
{
m_Device = new Device();
m_Device.SetCooperativeLevel(owner, CoOperativeLevel.Normal);
m_OwnsDevice = true;
}
// 設定通知的大小, 大小為播放一秒鐘聲音所需要的字節。這裡為什麼除以8,我不清楚
notifySize = (1024 > (format.AverageBytesPerSecond / 8)) ? (1024) : ((format.AverageBytesPerSecond / 8));
notifySize = (notifySize - (notifySize % format.BlockAlign));
m_BufferBytes = (notifySize * 4); //整體緩沖區的大小
BufferDescription desc = new BufferDescription(format);
//緩沖區具有控制音量的能力;
desc.ControlVolume = true;
//緩沖區具有控制位置的能力。
desc.ControlPositionNotify = true;
//設置緩沖區能取到當前的播放位置
desc.CanGetCurrentPosition = true;
//緩沖區不具有控制3D音效的能力;
desc.Control3D = false;
//SpecifIEs whether the buffer supports effects processing.
desc.ControlEffects = false;
//緩沖區具有控制頻率的能力;
desc.ControlFrequency = true;
//緩沖區具有控制左右聲道的能力;
desc.ControlPan = true;
//設置是否使用全局緩存
desc.GlobalFocus = true;
//設置緩沖區大小為整個緩沖區的大小
desc.BufferBytes = m_BufferBytes;
//創建輔助緩沖區
m_Buffer = new SecondaryBuffer(desc, m_Device);
//創建環形緩沖區
circularBuffer = new CircularBuffer((m_BufferBytes * 10));
InitNotifications();
m_Buffer.Play(0, BufferPlayFlags.Looping);
}
public SoundPlayer(Control owner, int sr, short bps, short ch)
: this(owner, null, DirectSoundManager.CreateWaveFormat(sr, bps, ch))
{
}
public SoundPlayer(Control owner, Device device, int sr, short bps, short ch)
: this(owner, device, DirectSoundManager.CreateWaveFormat(sr, bps, ch))
{
}
#endregion