views:

723

answers:

3

I'm using System.Windows.Media.MediaPlayer to play some sounds, and I would like to load these sounds from a ZIP file. It would be nice to be able to load these files as a stream directly from the zip file instead of having to unzip to a temp directory. However, MediaPlayer.open only accepts an URI.

So, is there a way to create a URI that will reference the contents of a stream? Something like an in-memory localhost? Is there any connector from Stream to URI?

+1  A: 

System.Media.SoundPlayer should do what you need (you can skip MediaPlayer and URIs altogether). It has a constructor that takes a stream.

MusiGenesis
+1  A: 

I'm using MediaPlayer for two major reasons:

  1. It supports concurrent streams playing at the same time (SoundPlayer does not support this)
  2. It allows me to retrieve the length/duration of the sound file.

Thanks!

A: 

Since you need to support polyphony, one approach is to PInvoke into the waveOutXXXX Windows API in order to play the sounds. Here is a good example of how to do this in C#:

http://69.10.233.10/KB/audio-video/cswavplay.aspx

This example also has code for reading info like duration, sample rate, bits per sample etc.

If you search, you may find claims that the waveOutXXXX API can only play one sound at a time. This was true in Windows 95/98, but is not true any longer.

By the way, SoundPlayer is probably the most frustrating .NET class. The .Play() method automatically stops playback of any other sound played by your process (it might be any other sound played by any .NET app) before starting, which is why you can't do polyphony with it. It would have taken Microsoft's worst intern less than a minute to add a .DontStopJustPlay() method or a StopFirst bool parameter to the .Play() method. It might have taken him until lunch time to add a Duration property.

Although waveOutXXXX is trickier than you would want from a well-designed modern API (and using it in .NET introduces additional problems), the one unmatched advantage it has is that it's come pre-installed on every single Windows computer since Windows 95, including Windows Mobile devices. Every other option (including MediaPlayer) means somebody will always have to install something.

MusiGenesis