Playing a Sound With Monotouch

audio, iphone, xamarin.ios

Solution

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.FromFilename("myMp3.mp3");
var audioPlayer = AVAudioPlayer.FromUrl(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

Problem

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?

Original source