/// <summary> /// 读取并写入数据的线程函数 /// </summary> private void ThdFetchAndWriteData() { _recordBlockSize = (int)GetNearest2N((uint)(aitask.SampleRate / 20)) * aitask.Channels.Count; //_recordBlockSize = (int)GetNearest2N((uint)(aitask.SampleRate / 20) * (uint)aitask.Channels.Count); byte[] bufferToFile = new byte[_recordBlockSize * sizeof(int)]; int[] tempBuff = new int[_recordBlockSize]; int[] tempBuffDeq = new int[_recordBlockSize + aitask.Channels.Count]; int currentElementCount = 0; long recordedCount = 0; //写入文件的点数(所有通道) _localPreviewBuffer = new JYCommon.CircularBuffer <int>(Math.Max(_recordBlockSize, (int)aitask.SampleRate * aitask.Channels.Count)); //流盘预览缓冲区建立,1s每通道 _previewDataConvertBuffer = new int[_localPreviewBuffer.BufferSize * 2, aitask.Channels.Count]; while (TaskDone == false) { //To Add: 以下添加从缓冲区取数据并存入文件 JYCommon.WaitEvent waitEvent = new JYCommon.WaitEvent(() => TaskDone || (aitask.AvailableSamples >= _recordBlockSize)); if (waitEvent.EnqueueWait(EventQueue, 100)) { currentElementCount = aitask.AvailableSamples; if (TaskDone == false && aitask.AvailableSamples >= _recordBlockSize) { _recordCnt += _recordBlockSize; aitask.ReadRawData(ref tempBuff, 1000); Buffer.BlockCopy(tempBuff, 0, bufferToFile, 0, _recordBlockSize * sizeof(int)); WriteDataToFile(bufferToFile, 0, _recordBlockSize * sizeof(int)); //写入文件 recordedCount += _recordBlockSize; //累加写入的点数 _recordedLength = (double)recordedCount / aitask.Channels.Count / aitask.SampleRate; if (_previewBufferLock.WaitOne(1)) { //如果放不下则,先清空,保证该缓冲区始终只有BlockSize那么多数据 if (_localPreviewBuffer.CurrentCapacity < _recordBlockSize) { _localPreviewBuffer.Dequeue(ref tempBuffDeq, ((_recordBlockSize - _localPreviewBuffer.CurrentCapacity) / aitask.Channels.Count + 1) * aitask.Channels.Count); } _localPreviewBuffer.Enqueue(tempBuff, _recordBlockSize); _previewBufferLock.ReleaseMutex(); ActivateWaitEvents(); } if (_recordedLength >= _recordLength) { TaskDone = true; } } } } _recordDone = true; }