Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

play mp3 with monotouch

I'm building an application using monotouch. Basically I need to play a mp3 as soon as the application loads. On the main.cs I added this snippet before pushing the main controller:

AVAudioPlayer player = new AVAudioPlayer();
NSUrl mediaFile = NSUrl.FromFilename("Content/Audio/music1.mp3");

player = AVAudioPlayer.FromUrl(mediaFile);
player.Delegate = new PlayerDelegate();

if(player.PrepareToPlay()){
  player.Play();
}

But when I start the application I can hear the sound for about half second and then nothing. Is this code correct or there is something wrong?

Thanks

like image 556
iFrankz Avatar asked Oct 12 '11 20:10

iFrankz


1 Answers

It's hard to provide an answer without more context, like more code :-)

I suspect your AVAudioPlayer, if used as a local variable, could be collected by the garbage collector (GC) when the method (is it FinishedLaunching ?) returns.

If this is the case then promoting your local player variable into a field would ensure a reference is kept to the AVAudioPlayer instance and should allow it to play without being interrupted (or crashing).

If I'm wrong then please edit your question and provide us with more context and we should be able to help you further.

like image 190
poupou Avatar answered Oct 25 '22 15:10

poupou