Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to play chunks of mp3 bytes from sql server, transferred to desktop client (by wcf) using C#?

I have "chunks" of audio(in mp3 format) on a sql database i.e, you can imagine a mp3 file ,divided to equal size of chunks and each chunk is saved on a record on a sql server db. these chunks are returned to the desktop client(s) via a WCF service. of course the client asks for the next chunk when it receives one.(they will be received in order ,so the header comes first!) here is the question ,how may I play this received chunks in my desktop app one by one in sequent? can i play them back to back using each chunk to buffer the player?

please notice : -the desktop client is in C# -the player can be wmp if it works for this purpose! -chunks are saved in bytes -for some reasons the "chunk on sql " system is already implemented by someone else..i just need to find a way to play them like a stream on desktop

thanks!

like image 658
Arash Mhd Avatar asked Jan 25 '13 08:01

Arash Mhd


1 Answers

Assuming your mp3 player can play from a System.IO.Stream object, implement your own stream class with the following

    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;
    }

What this does is place the chunks of data into a queue. The Read method reads them out in order they were added.

This code will only read 1 chunk at a time, but could be expanded to read on a separate thread and buffer up a number of chunks.

like image 74
shimpossible Avatar answered Nov 14 '22 22:11

shimpossible