MonoTouch: Playing sound

杀马特。学长 韩版系。学妹 提交于 2019-12-04 10:41:47

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

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.

Has AlTaiar

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