views:

640

answers:

2

No matter what I try (build -> content, NSUrl, filename) I get a 'null exception': file not found when I try to play a .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 also try combinations using the folder name "images/MatchGame.caf" and moving MatchGame.caf into the root folder.

What am I missing? Thanks a lot.

Here is a link to a video of adding the sound in monotouch. http://www.screencast.com/t/MmE0ZmFh What is wrong?

+1  A: 

You need the first line:

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

Then make sure that your audio file is included in the application by making sure that your CAF file is flagged as "Content" in the Properties pane, otherwise the file is not copied to the resulting application package (your .app)

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

http://wiki.monotouch.net/HowTo/Images/Add%5Fan%5FImage%5Fto%5Fyour%5FProject

Additionally, this is a good resource for where you should store files:

http://wiki.monotouch.net/HowTo/Files/HowTo%3a%5FStore%5FFiles

miguel.de.icaza
I read all the documentation and tried everything. I can't get it to play a sound. Can you please give me the sample code?
Bryan
Can you please see this video and tell me what is wrong? http://www.screencast.com/t/MmE0ZmFh
Bryan
You are getting a NullReferenceException, so chances are, you do not have a valid file there that you can use with SystemSound (it is limited to 30 second samples). Use the APIs that we actually recommended you use, not SystemSound.
miguel.de.icaza
A final note, you can use also:var sound = new SystemSound (url)Instead of SystemSound.FromFile if you want to get a more detailed exception instead of the "null" in case of errors.
miguel.de.icaza
+1  A: 

Bryan,

From looking at your screencast - you are trying to play a mp3 file and not a caf file. Mp3 files are encoded differently and will not play with the SystemSound class that's there (I can't remember if you can do this in Obj-C or not.)

You'll want to use the AVFoundation Namespace and AVAudioPlayer class.

using Monotouch.AVFoundation;

var mediaFile = NSUrl.FromFile("myMp3.mp3");
var audioPlayer = new AVAudioPlayer(mediaFile);
audioPlayer.FinishedPlaying += delegate { audioPlayer.Dispose(); };
audioPlayer.Play();

You might need to tweak the code above - I don't have MonoDevelop to hand but that should help you a little further.

Cheers,

ChrisNTR

chrisntr
Thanks so much! Nailed it.
Bryan