MonoTouch: Playing sound

血红的双手。 提交于 2019-12-06 06:48:25

问题


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


来源:https://stackoverflow.com/questions/9905008/monotouch-playing-sound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!