4

I'm trying to play a sound file in monotouch but it gets cut off after a second or two. Here is the code I'm using to play the sound:

SoundFileName = filename; 
var sound = SystemSound.FromFile(filename);
sound.PlaySystemSound();

It's an MP3 file that I'm trying to play. Again, I hear it for a brief second and then it gets cut. I added a thread.sleep() line afterwards and THEN it'll play throughout.

But that's not ideal because the length of the mp3 files that I'm playing could vary. Any help would be greatly appreciated. Thank you.

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334
Shaz
  • 2,676
  • 1
  • 22
  • 22

2 Answers2

6

You need to declare your sound object at the form or class level. In your posted sample, sound is only scoped to the function, so as soon as the method ends the variable goes out of scope and is disposed before the sound finished playing. Thread.sleep works because that call prevents the method from ending for a while (and thus prevents sound from going out of scope).

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334
0

You may also want to look at this question: Playing a sound with MonoTouch

I don't think SystemSound is intended to use with MP3's of open duration.

Community
  • 1
  • 1
Jason
  • 86,222
  • 15
  • 131
  • 146
  • The `AVAudioPlayer` in iOS (which I assume is what MonoTouch is wrapping) works the same as `SoundPlayer` in .NET - it preloads the entire file before beginning play, which means it's not really ideal for a song-length MP3 either. I dunno, maybe MonoTouch implements `SoundPlayer` by wrapping a different iPhone API (there's at least 3 to choose from that I know of)? – MusiGenesis May 10 '11 at 01:08