Fixing a Streaming Issue in ShoutStreamSource on Windows Phone

DZone 's Guide to

Fixing a Streaming Issue in ShoutStreamSource on Windows Phone

· Mobile Zone ·
Free Resource

Music streaming is a practice that is used by many Windows Phone applications, incuding but not limited to MetroRadio and Spotify. This weekend I got the chance to experiment with this too, and I had a Shoutcast stream to work with. Although I could still work with the default implementation through MediaElement, which supports streaming to a limited extent, or AudioPlayerAgent, I wanted to research the internals of the process.

Tim Heuer posted two articles on this topic that interested me:

There is a very basic project that implements the MediaStreamSource for a Shoutcast stream, available here.

Right down my alley, so I downloaded the source and tried to re-write some parts of it to fit my needs. It seemed to work fine, however whenever I started the streaming, the audio was extremely choppy. First, I thought there was a problem with the stream itself, but after a quick check in the browser, it seemed like the stream was doing just fine.

It turns out that there is a bad segment in the code. Take a look (RadioStream -> GetAsyncData):

byte read;
      read = (byte)r.ReadByte();

There is no streaming buffer, as such, so the data is handled as it comes in - byte by byte. This is not something that should be done. Instead, I rewrote it like this:

byte[] buffer = new byte[128*1024];
while (ContinueStreaming)
	int read = stream.Read(buffer, 0, buffer.Length);
	mediaStream.Write(buffer, 0, read);

There is a 128K buffer that is being written to a media stream, that is later handled by the application. The size can be ultimately adjusted, but with the current value I found it to be optimal.

Also, if you are working with Shoutcast and don't want to write the media parser on your own like I did, you might want to check Shoutcast MediaStreamSource - a much more mature project with many performance and parsing optimizations.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}