MonoTouch: Playing sound

2019-04-09 18:18发布

问题:

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.

回答1:

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");


回答2:

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.



回答3:

In most cases it would be the File does not exist. If you are like me, and you made sure that the file exists. Ensure the following:

  1. The Path of the file should be relative to your Class (ie: Sounds\beep.wav) (Absolute path did not work for me on the simulator)
  2. Ensure that you are defining the SoundSystem in the class level. This is because MT has a ver agressive Garbage Collector and could dispose your SoundSystem before it even starts playing. see this question