Reputation: 17193
I'm building an application that should play audio from a server. The app should play the audio at the same time that it receives the bytes from the server (similarily to how YouTube loads your video while playing it).
Problem is, I can't read from a stream (in order to play it) while at the same time writing into it. Streams don't allow that.
I've been thinking how I can acheive this but I'm not sure. I searched online but found nothing that solves this problem. Would appreciate advice. What's a preferably simple and good way to approach this problem?
Upvotes: 3
Views: 441
Reputation: 873
You need a buffer-file where you can read and write the data (you wont get your data in that speed which you want to play it). Then you have to lock the Stream when you read data (buffering for example 200kb) so your streamwriter have to wait. after that you have to lock the stream to write data from server to file.
edit:
Here is an example 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);
}
});
}
}
Upvotes: 4