28

I want to stream data from a server into a MediaElement in my Windows 8 Store (formerly Metro) app. However, I need to "record" the stream while it is streaming, so it can be served from cache if re-requested, so I don't want to feed the URL directly into the MediaElement.

Currently, the stumbling block is that MediaElement.SetSource() accepts an IRandomAccessStream, not a System.IO.Stream, which is what I get from HttpWebResponse.GetResponseStream().

The code I have now, which does not work:

var request = WebRequest.CreateHttp(url);
request.AllowReadStreamBuffering = false;
request.BeginGetResponse(ar =>
                {
                    var response = ((HttpWebResponse)request.EndGetResponse(ar));
                    // this is System.IO.Stream:
                    var stream = response.GetResponseStream(); 
                    // this needs IRandomAccessStream:
                    MediaPlayer.SetSource(stream, "audio/mp3");
                }, null);

Is there a solution that allows me to stream audio, but allows me to copy the stream to disk when it has finished reading from the remote side?

Vegard Larsen
  • 12,827
  • 14
  • 59
  • 102
  • have you figured it out? actually i do not need to store it, i just want to stream it directly. – esskar Oct 19 '12 at 00:52
  • @esskar Not really. Streaming directly works great by just providing the URL, or a `InMemoryRandomAccessStream`. The problem is distributing the stream to two different locations. – Vegard Larsen Oct 19 '12 at 07:39
  • thanks for the information. i tried to set the `.Source` property directly, but it does not work out for me. (I get a null-ref exceptions somewhere in the deep), and i have not figured out how to create a `IRandomAccessStream` form an URL. but i will work on it today. – esskar Oct 19 '12 at 07:44
  • You don't need an `IRandomAccessStream`, simply set `me.Source = new Uri("http://...");` and it should work... – Vegard Larsen Oct 19 '12 at 10:56

2 Answers2

0

I haven't experimented with the following idea, but it might work: You could start streaming the web data into a file and then, after a few seconds (for buffering), pass that file to the MediaElement.

I noticed that MediaElement can be picky about opening a file that is being written into, but I have seen it work. Though, I can't say why it sometimes work and why it sometimes doesn't.

Pierre Henri K
  • 278
  • 1
  • 9
0

I guess this would help you to convert Stream to IRandomAccessStream

InMemoryRandomAccessStream  ras = new InMemoryRandomAccessStream();

using (Stream stream = response.GetResponseStream();)
  {
    await stream.CopyToAsync(ras.AsStreamForWrite());
  }
Aman Chaudhary
  • 200
  • 1
  • 2