Play sound with Monotouch

No matter what I try (build β†’ content, NSUrl, filename), I get a "null exception": the file was not found when I try to play the .caf sound file in monotouch.

//var path = NSBundle.MainBundle.PathForResource("MatchGame", "caf"); //var gameSong = SystemSound.FromFile( new NSUrl(path, false)); var gameSong = SystemSound.FromFile("MatchGame.caf"); gameSong.PlaySystemSound(); 

I am also trying to use combinations by using the folder name "images / MatchGame.caf" and moving MatchGame.caf to the root folder.

What am I missing? Thank you very much.

Here is a link to the video with the addition of sound in a single point. http://www.screencast.com/t/MmE0ZmFh What is wrong?

+3
source share
2 answers

Brian,

From looking at your screencast, you are trying to play an mp3 file, not a file in a cafe. Mp3 files are encoded differently and will not play with the SystemSound class, which is (I cannot remember if you can do this in Obj-C or not.)

You want to use the AVFoundation namespace and the AVAudioPlayer class.

 using Monotouch.AVFoundation; var mediaFile = NSUrl.FromFilename("myMp3.mp3"); var audioPlayer = AVAudioPlayer.FromUrl(mediaFile); audioPlayer.FinishedPlaying += delegate { audioPlayer.Dispose(); }; audioPlayer.Play(); 

You may need to tweak the code above - I don't have MonoDevelop, but that should help you a bit further.

Greetings

Chrisntr

+8
source

You need the first line:

var path = NSBundle.MainBundle.PathForResource ("MatchGame", "caf");

Then make sure your audio file is included in the application, making sure that your CAF file is marked as β€œContent” in the β€œProperties” panel, otherwise the file will not be copied to the resulting application package (your .app)

You can follow the steps described here (they are for images, but apply to audio files):

http://wiki.monotouch.net/HowTo/Images/Add_an_Image_to_your_Project

It is also a good resource for storing files:

http://wiki.monotouch.net/HowTo/Files/HowTo%3a_Store_Files

+6
source

All Articles