Archive for the ‘WCF’ Category

Streaming MP3 audio from a WCF REST service

June 29, 2009

For a project i am working on in my spare time, i needed to stream MP3 audio from a REST service, implemented in WCF. I was supprised at how easy this was. It’s as simple as setting the response content type and returning a stream:

IAudioDemoService.cs method definition:

[OperationContract]
[WebInvoke(
Method = "GET",
UriTemplate = "/AudioStream")]
Stream GetAudioStream();

AudioDemoService.cs method implementation:

public Stream GetAudioStream()
{
	WebOperationContext.Current.OutgoingResponse.ContentType = "audio/mpeg";
	return new FileStream(@"c:\AudioFile.mp3", FileMode.Open);
}

(actually the content type isn’t strictly nessesary, but it enables a client to identify the information in the stream – a browser for instance might use it to select an appropriate application for processing)

Easy!