How can I play an audio stream and download it at the same time?

I am creating an application that needs to play audio from a server. The application should play audio at the same time it receives bytes from the server (similar to how YouTube downloads your video during playback).

The problem is, I cannot read from the stream (to reproduce it) and at the same time write to it. Threads don't allow this.

I was thinking how can I achieve this, but I'm not sure. I searched the internet but couldn't find anything that solves this problem. Thank the advice. What's the preferred simple and good way to approach this problem?

+3


source to share


1 answer


You need a spooled file where you can read and write data (you won't get your data at the speed you want to play back). Then you need to block the Stream when you are reading data (for example buffering 200kb) so that your Stream has to wait. after that you need to block the stream to write data from the server to the file.

change:



Here's an example of what I mean:

class Program
{
    static FileStream stream;
    static void Main(string[] args)
    {
        stream = File.Open(@"C:\test", FileMode.OpenOrCreate);
        StreamWriterThread();
        StreamReaderThread();
        Console.ReadKey();
    }
    static void StreamReaderThread()
    {
        ThreadPool.QueueUserWorkItem(delegate
        {
            int position = 0; //Hold the position of reading from the stream
            while (true)
            {
                lock (stream)
                {
                    byte[] buffer = new byte[1024];
                    stream.Position = position;
                    position += stream.Read(buffer, 0, buffer.Length); //Add the read bytes to the position

                    string s = Encoding.UTF8.GetString(buffer);
                }
                Thread.Sleep(150);
            }
        });
    }
    static void StreamWriterThread()
    {
        ThreadPool.QueueUserWorkItem(delegate
        {
            int i = 33; //Only for example
            int position = 0; //Holds the position of writing into the stream
            while (true)
            {
                lock (stream)
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(new String((char)(i++),1024));
                    stream.Position = position;
                    stream.Write(buffer, 0, buffer.Length);
                    position += buffer.Length;
                }
                i%=125;//Only for example
                if (i == 0) i = 33;//Only for example
                Thread.Sleep(100);
            }
        });
    }
}

      

+4


source







All Articles