views:

339

answers:

3

I'm attempting to use a large number of short sound samples in a game I'm creating in Silverlight 2. The samples are less than 2 seconds long.

I would prefer to load all the audio samples onto the canvas during the initualization. I have been adding the media element to the canvas and a generic list to manage it. So far, it appears to work.

When I play the sample the first time, it plays perfectly. If it has finished playing and I want to re-use the same element, it cuts off the first part of the sound. To play the sample again, I stop and play the media element.

Is there another method I should use the samples so that the audio is not clipped and good performance is obtained?

+1  A: 

Some comments:

From MSDN: Try to limit the number of MediaElement objects you have in your application at once. If you have over one hundred MediaElement objects in your application tree, regardless of whether they are playing concurrently or not, MediaFailed events may be raised. The way to work around this is to add MediaElement objects to the tree as they are needed and remove them when they are not.

You could try to seek to the start of the sample to reset the point currently being played before re-using it with:

mediaelement.Position = new TimeSpan();

See also MSDNs MediaElement.Position.

Rutger Nijlunsing
+1  A: 

Also, it's probably a good idea to make sure that all of your audio samples are brought down to the client side initially. Depending on how you set it up, it's possible that the MediaElements are using their progressive download functionality to get the media files from the server. While there's nothing wrong with this per se (browser caching should be helping you out after the initial download), it does mean that you have to deal with the browser cache, and there are some potential issues there.

Possible steps to try:

  1. Mark your audio files as "Content". This will get them balled up in the .xap.
  2. Load your audio files into MemoryStreams (see Application.GetResourceStream method) and call MediaElement.SetSource().

HTH, Erik

Erik Mork
In Silverlight 3, I set them to "Resource" and used the memory streams. That comment helped a lot.
BenMaddox
A: 

One techique you can use, although I'm not sure how well it will work in Silverlight, is create one large file with all of your samples joined together (probably with a half-second or so of silence between each). Figure out the timecode for each sample and seek the media element to that position and play. You'll only need as many media elements as simultaneous sounds you want to play.

Talljoe
I haven't seen that approach mentioned before. I'll look into it.
BenMaddox