如何播放音频流并同时加载到其中?

时间:2014-12-23 22:23:04

标签: c# multithreading audio stream

我正在构建一个应该从服务器播放音频的应用程序。应用程序应在从服务器接收字节的同时播放音频(类似于YouTube在播放视频时加载视频的方式)。

问题是,在写入流的同时,我无法从流中读取(为了播放它)。 Streams不允许这样做。

我一直在想如何实现这个目标,但我不确定。我在网上搜索但发现没有解决这个问题。会很感激的建议。什么是解决这个问题的最佳简单方法?

1 个答案:

答案 0 :(得分:4)

您需要一个缓冲文件,您可以在其中读取和写入数据(您不会以您想要播放的速度获取数据)。 然后,当您读取数据时,您必须锁定Stream(例如缓冲200kb),因此您的编写者必须等待。 之后,您必须锁定流以将数据从服务器写入文件。

编辑:

以下是我的意思:

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);
            }
        });
    }
}
相关问题