私有方法#region 私有方法
private void InitNotifications()
{
notifyThread = new Thread(NotifyThreadHandler);
isRunning = true;
notifyThread.IsBackground = true;
notifyThread.Start();
notificationEvent = new AutoResetEvent(false);
notify = new Notify(m_Buffer);
//把整個緩沖區分成4個緩沖區片段,每播放4分之一就會給寫線程發送一個信號
for (int i = 0; i < 4; i = (i + 1))
{
positionNotify.Offset = (((notifySize * i) + notifySize) - 1);
positionNotify.EventNotifyHandle = notificationEvent.SafeWaitHandle.DangerousGetHandle();
}
notify.SetNotificationPositions(positionNotify, 4);
nextWriteOffset = 0;
}
private void NotifyThreadHandler()
{
while (isRunning)
{
try
{
notificationEvent.WaitOne(-1, true);
Play();
}
catch (Exception)
{
}
}
}
private void Play()
{
try
{
try
{
int currentPlayPosition;
int currentWritePosition;
m_Buffer.GetCurrentPosition(out currentPlayPosition, out currentWritePosition);
//得到剛剛播放完的緩沖區片段,這個片段需要用新的數據去填充
int lockSize = (currentWritePosition - nextWriteOffset);
//todo:這裡不知道什麼時候會發生
if (lockSize < 0)
{
lockSize = (lockSize + m_BufferBytes);
}
//對齊需要填充的緩沖區片段
lockSize = (lockSize - (lockSize % notifySize));
if (0 != lockSize)
{
if (lockSize == m_BufferBytes)
{
}
byte[] data = new byte[lockSize];
if (circularBuffer.Read(data) > 0)
{
m_Buffer.Write(nextWriteOffset, data, LockFlag.None);
nextWriteOffset = (nextWriteOffset + lockSize);
//如果完整寫完一次緩沖區,那麼把寫數據指針放到緩沖區的最開始,
//因為前面設置了m_Buffer.Play(0, BufferPlayFlags.Looping);
//所以系統在播放緩沖區後會自動重新開始播放緩沖區起始處的聲音數據
nextWriteOffset = (nextWriteOffset % m_BufferBytes);
}
}
}
catch (Exception)
{
}
}
finally
{
}
}
#endregion