I am trying to play a short sound when user taps on the specific button. But the problem is that I always receive Object reference not set to an instance object. means Null!
I first tried MonoTouch.AudioToolBox.SystemSound.
MonoTouch.AudioToolbox.AudioSession.Initialize();
MonoTouch.AudioToolbox.AudioSession.Category = MonoTouch.AudioToolbox.AudioSessionCategory.MediaPlayback;
MonoTouch.AudioToolbox.AudioSession.SetActive(true);
var t = MonoTouch.AudioToolbox.SystemSound.FromFile("click.mp3");
t.PlaySystemSound();
Let me notice that "click.mp3" is in my root solution folder and it is flagged as Content.
The other approach is MonoTouch.AVFoundation.AVAudioPlayer
.
var url = NSUrl.FromFilename("click.mp3");
AVAudioPlayer player = AVAudioPlayer.FromUrl(url);
player.FinishedPlaying += (sender, e) => { player.Dispose(); };
player.Play();
But same error. I googled it and I see that many people has this problem. We need to know whether it is a bug or not.
About using SystemSound
and MP3 see this question and answer: Playing a Sound With Monotouch
For AVAudioPlayer
be aware that the following pattern is dangerous:
AVAudioPlayer player = AVAudioPlayer.FromUrl(url);
player.FinishedPlaying += (sender, e) => { player.Dispose(); };
player.Play();
since Play
is asynchronous. This means the managed player
instance can get out of scope before FinishedPlaying
occurs. In turn this out of scope means the the GC could already have collected the instance.
A way to fix this is to promote the player
local variable into a type field. That will ensure the GC won't collect the instance while the sound is playing.
Your code looks correct (I compared to the code here, which is able to play audio).
What might be the problem is that the audio file isn't included in the app bundle somehow. You can easily check it with this code:
if (!System.IO.File.Exists ("click.mp3"))
Console.WriteLine ("bundling error");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With