Search code examples
c#.netstreamnaudioseek

Stream wrapper to make Stream seekable?


I have a readonly System.IO.Stream implementation that is not seekable (and its Position always returns 0). I need to send it to a consumer that does some Seek operations (aka, sets the Position) on the stream. It's not a huge seek -- say +/- 100 from the current position. Is there an existing Stream wrapper that will add a buffering ability to the stream for simple Seek operations?

Update: I should add that my consumer is the NAudio Mp3FileReader. I really just need a way to play a (slowly and indefinitely) streaming MP3. I think it's a bug that NAudio expects to be able to seek their data source at will.


Solution

  • Seeking forwards is easy enough (just read), but you can't seek backwards without buffering. Maybe just:

    using(var ms = new MemoryStream()) {
        otherStream.CopyTo(ms);
        ms.Position = 0;
        // now work with ms
    }
    

    This, however, is only suitable for small-to-moderate streams (not GB), that are known to end (which streams are not requires to do). If you need a larger stream, a FileStream to a temp-file would work, but is significantly more IO-intensive.