Question

I've got an ArrayList which contains a number of sound files as elements. A foreach loop iterates this collection, and plays each note.

The problem is that when the program is run, only the last note plays, but when debugging, it goes through all the elements and each one is played.

The sound is represented as an object of my 'MusicNote' class. I cant understand what the problem is, as when debugging, it works perfectly.

Was it helpful?

Solution

According to http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx player.Play() starts a new thread which means that it returns long before playing the file is finished...

Use player.PlaySync() instead - either in your main thread or (since it is blocking) on a separate thread.

Remark: When debugging multi-threaded programs sometimes behave differently - esp. when you step through...

OTHER TIPS

I've digged through some old code and I've implemented it like this (in WP7)

you can try calling:

player.PlaySync();

The problem is that SoundPlayer.Play() is asynchronic, so it is not going to block your foreach

it seems that the reasonis because on each iteration of the loop you are setting the file before it has a chance play. Only the final iteration has a chance to load and play.

if you want to play the clips simultaneously, i think you'll need to do this in multiple threads where each thread plays the clip.

if you want to play it sequentially i would look into building a playlist, and then loading that.

You need to initialize the output to prevent the overhead from skipping the start. I'm not sure how you can do this though outside game engine environment. Maybe you could add a fake note to fit the gap of fixed length or error length.

I hope this helps! I understand it's not a great answer but you can't blame a guy for trying right ;)

P.S. Look at jasons playlist idea, it's nice

How many items are in the noteList? What do you mean by "when debugging"? What do you mean by "when the program is run"?

Furthermore, Play() is asynchronously, so I guess all sounds are played simultaneously so it seems like only one is played. You can call PlaySync() instead. It will block however, so you might want to do it on a separate thread.

What is note? What are you using to play? What kind of files are they?

It may well be that you call play, and it starts to play the first note, but it doesn't block goes to the next note and the first note is canceled and so on until the last note that is allowed to complete because nothing comes after it. Place a wait after the play to see if that is the problem, if it is then you need to find a way to wait for the notes to finish before going to the next.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top