MonoTouch: sound reproduction

I try to play a short sound when a user clicks on a specific button. But the problem is that I always get a reference to an object that is not set to an instance object . mean null!

First I 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 folder with the root solution, and it is marked as Content. Another 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 the same mistake. I was looking for him, and I see that many people have this problem. We need to know if this is a mistake or not.

+4
source share
3 answers

Your code looks correct (I am compared to the code here that is capable of playing audio).

What could be the problem, since the audio file is not included in the application package. You can easily check it with this code:

 if (!System.IO.File.Exists ("click.mp3")) Console.WriteLine ("bundling error"); 
+4
source

For using SystemSound and MP3, see this question and answer: Play sound with Monotouch

For AVAudioPlayer remember that the following template is dangerous:

 AVAudioPlayer player = AVAudioPlayer.FromUrl(url); player.FinishedPlaying += (sender, e) => { player.Dispose(); }; player.Play(); 

since Play is asynchronous. This means that the managed instance of player can go out of scope before FinishedPlaying happens. This, in turn, is out of scope, which means that the GC could already assemble an instance.

The way to fix it is to move the local variable player into the type field. This ensures that the GC will not collect an instance during audio playback.

+7
source

In most cases this will be File does not exist. If you are like me and you make sure the file exists. Make sure that:

  • The file path should be relative for your class (i.e.: Sounds\beep.wav ) (for my simulator, the Absolute path does not work for me)
  • Make sure you define SoundSystem in class level . This is because MT has a ver agressive Garbage Collector and can use your SoundSystem before it starts playing. see question
+1
source

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


All Articles