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
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 itFinishedLaunching?) returns.If this is the case then promoting your local
playervariable into a field would ensure a reference is kept to theAVAudioPlayerinstance 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.