This recipe illustrates how to record a sound file from the active audio input (either the built-in microphone or the audio input) using the AVAudioRecorder class.
Recipe
The easiest way to record sound in iOS is to use the built-in AVAudioRecorder class:
- Declare class-level variables:
AVAudioRecorder recorder; NSError error = new NSError(new NSString("com.xamarin"), 1); NSUrl url; NSDictionary settings;
- Specify the recording format and location to save the recording to. The
recording format is specified as an NSDictionary with two NSObject arrays
containing the keys and values of the format specification:
//Declare string for application temp path and tack on the file extension string fileName = string.Format ("Myfile{0}.wav", DateTime.Now.ToString ("yyyyMMddHHmmss")); string tmpdir = NSBundle.MainBundle.BundlePath + "/tmp"; string audioFilePath = Path.Combine(tmpdir, fileName); Console.WriteLine("Audio File Path: " + audioFilePath); url = NSUrl.FromFilename(audioFilePath); //set up the NSObject Array of values that will be combined with the keys to make the NSDictionary NSObject[] values = new NSObject[] { NSNumber.FromFloat (44100.0f), //Sample Rate NSNumber.FromInt32 ((int)MonoTouch.AudioToolbox.AudioFormatType.LinearPCM), //AVFormat NSNumber.FromInt32 (2), //Channels NSNumber.FromInt32 (16), //PCMBitDepth NSNumber.FromBoolean (false), //IsBigEndianKey NSNumber.FromBoolean (false) //IsFloatKey }; //Set up the NSObject Array of keys that will be combined with the values to make the NSDictionary NSObject[] keys = new NSObject[] { AVAudioSettings.AVSampleRateKey, AVAudioSettings.AVFormatIDKey, AVAudioSettings.AVNumberOfChannelsKey, AVAudioSettings.AVLinearPCMBitDepthKey, AVAudioSettings.AVLinearPCMIsBigEndianKey, AVAudioSettings.AVLinearPCMIsFloatKey }; //Set Settings with the Values and Keys to create the NSDictionary settings = NSDictionary.FromObjectsAndKeys (values, keys); //Set recorder parameters recorder = AVAudioRecorder.ToUrl(url, settings, out error); //Set Recorder to Prepare To Record recorder.PrepareToRecord();
- Call PrepareToRecord, which initializes the recording framework.
//Set Recorder to Prepare To Record recorder.PrepareToRecord();
- Call Record, when you’re ready to begin recording the audio.
recorder.Record();
- When you’re finished recording call the Stop method on the
recorder:
this.recorder.Stop();
Additional Information
iOS has a number of powerful frameworks for working with audio. The technique shown in this recipe is one of the simplest, but there are a number of others that serve different purposes. For more information, see the Using Audio section of the Multimedia Programming Guide in the Apple iOS documentation.