Play mp3 with monotouch

I am creating an application using monotouch. Basically I need to play mp3 as soon as the application loads. On main.cs, I added this snippet before clicking on 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 launch the application, I hear a sound for about one and a half seconds, and then nothing. Is this code right or is something wrong?

thanks

+6
source share
3 answers

It is difficult to provide an answer without additional context, for example, more code :-)

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

If so, then moving the local player variable into the field ensures that the link is stored in the AVAudioPlayer instance and should allow it to play without interruption (or failure).

If I am mistaken, please edit your question and provide us with more context, and we can help you in the future.

+7
source

Try registering for AVAudioPlayerDelegate and start playing music again in the audioPlayerEndInterruption method.

0
source

Now it is very simple:

  //enable audio AudioSession.Initialize(); //load the sound sound = SystemSound.FromFile("Sounds/rev.wav"); sound.PlaySystemSound(); 
0
source

Source: https://habr.com/ru/post/899164/


All Articles