假设您的 mp3 播放器可以从 System.IO.Stream 对象播放,请使用以下代码实现您自己的流类
private byte[] GetDataBlock()
{
while (data.Count == 0)
{
//TODO: Read More Data from the database
index = 0;
}
return data.Peek();
}
private void RemoveDataBlock()
{
data.Dequeue();
index = 0;
}
Queue<byte[]> data = new Queue<byte[]>();
int index = 0;
public override int Read(byte[] buffer, int offset, int count)
{
int left = count;
int dstIndex = 0;
while (left > 0)
{
byte[] front = GetDataBlock();
int available = front.Length - index;
// how much from the current block can we copy?
int length = (available <= left) ? available : left;
Array.Copy(front, index, buffer, dstIndex, length);
dstIndex += length;
left -= length;
index += length;
// read all the bytes in the array?
if (length == available)
{
RemoveDataBlock();
}
}
return count;
}
这样做是将数据块放入队列中。Read 方法按添加顺序读取它们。
此代码一次只能读取 1 个块,但可以扩展为在单独的线程上读取并缓冲多个块。