{"id":3525,"date":"2012-12-09T15:29:47","date_gmt":"2012-12-09T10:29:47","guid":{"rendered":"http:\/\/aasims.wordpress.com\/?p=3525"},"modified":"2025-04-09T12:23:21","modified_gmt":"2025-04-09T12:23:21","slug":"how-to-record-audio-in-ios-application","status":"publish","type":"post","link":"https:\/\/aasimnaseem.com\/blog\/how-to-record-audio-in-ios-application\/","title":{"rendered":"How to record Audio in iOS Application"},"content":{"rendered":"<p>Hello dev mate;<a href=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/09\/how-to-record-audio-in-ios-application\/xcodelogo\/\" rel=\"attachment wp-att-3536\"><img loading=\"lazy\" decoding=\"async\" class=\" wp-image-3536 alignright\" src=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/xcodelogo.png\" alt=\"XcodeLogo\" width=\"143\" height=\"140\" \/><\/a><br \/>\nHope you had a good weekend and refreshing Monday;<\/p>\n<p>Today we&#8217;ll learn how to record audio in iOS application; Now a days, I&#8217;m working on an application where I need to record voice of user for some processing; I tried some framework classes from iOS sdk in a test project and here are my findings;<\/p>\n<p>So lets start;<\/p>\n<p><!--more--><br \/>\nPriminarly we&#8217;ll use following classes and framework<\/p>\n<p><strong>AVFoundation.framwork<br \/>\n<\/strong>Provides set of APIs to record\/play audio and video in iOS application;<\/p>\n<p><strong>AVAudioRecorder<br \/>\n<\/strong>Called an audio recorder, provides audio recording capability in your application.<\/p>\n<p><strong>AVAudioPlayer<br \/>\n<\/strong>An instance of the AVAudioPlayer class called an audio player, provides playback of audio data from a file or memory;<\/p>\n<h3><strong>1. Project Creation and Setup<\/strong><\/h3>\n<p>1. Open you Xcode and create new project .i.e. File -&gt; New -&gt; New Project or \u00a0press Command+Shift+N<\/p>\n<p>2. Create\u00a0<em>Single View Application<\/em>\u00a0and<em>\u00a0<\/em>provide suitable name; In my case, its\u00a0<em>AudioRecordingExample<\/em>;<\/p>\n<p>3. Select project location etc and save it; Your project should look like this<\/p>\n<p><a href=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/09\/how-to-record-audio-in-ios-application\/screen-shot-2012-12-09-at-3-31-58-pm\/\" rel=\"attachment wp-att-3530\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3530\" src=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/screen-shot-2012-12-09-at-3-31-58-pm.png\" alt=\"Screen Shot 2012-12-09 at 3.31.58 PM\" width=\"325\" height=\"342\" \/><\/a><\/p>\n<p>4. Add required framework to your project .i.e. AVFoundation; For this select your project in Navigator, then select Target at right sight panel; Go to\u00a0<em>Build Phases,\u00a0<\/em>chose\u00a0<em>Linke Binary with Libraries; <\/em>Press<em>\u00a0+<\/em>\u00a0button from botom and chose <em>AVFoundation<\/em>\u00a0from list;<\/p>\n<p><a href=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/09\/how-to-record-audio-in-ios-application\/screen-shot-2012-12-09-at-3-37-41-pm\/\" rel=\"attachment wp-att-3533\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3533\" src=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/screen-shot-2012-12-09-at-3-37-41-pm.png\" alt=\"Screen Shot 2012-12-09 at 3.37.41 PM\" width=\"600\" height=\"584\" \/><\/a><\/p>\n<p>After adding framework, you libraries should look like this;<\/p>\n<p><a href=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/09\/how-to-record-audio-in-ios-application\/screen-shot-2012-12-09-at-3-38-01-pm\/\" rel=\"attachment wp-att-3532\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3532\" src=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/screen-shot-2012-12-09-at-3-38-01-pm.png\" alt=\"Screen Shot 2012-12-09 at 3.38.01 PM\" width=\"604\" height=\"185\" \/><\/a><\/p>\n<h3><strong>2. Interface Design<\/strong><\/h3>\n<p>First open the ViewController.xib file and make your screen like this; I&#8217;m sure I don&#8217;t need to explain how to design it; (:<\/p>\n<p><strong><a href=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/09\/how-to-record-audio-in-ios-application\/screen-shot-2012-12-09-at-4-14-08-pm\/\" rel=\"attachment wp-att-3534\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3534\" src=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2012\/12\/screen-shot-2012-12-09-at-4-14-08-pm.png\" alt=\"Screen Shot 2012-12-09 at 4.14.08 PM\" width=\"377\" height=\"598\" \/><\/a><\/strong><\/p>\n<h3><strong>3. Declaring Variable in .h file;<\/strong><\/h3>\n<p>Open you ViewController.h file from Navigator and add the following code there;<\/p>\n<p>Implement the following\u00a0AVAudioRecorderDelegate and AVAudioPlayerDelegate in your \u00a0viewController;<\/p>\n<p>[code lang=&#8221;objc&#8221;]<\/p>\n<p>@interface ViewController : UIViewController &lt;AVAudioRecorderDelegate, AVAudioPlayerDelegate&gt;<\/p>\n<p>[\/code]<\/p>\n<p>Include AVFoundation.h in your import section;<\/p>\n<p>[code lang=&#8221;objc&#8221;]<\/p>\n<p>#import &lt;AVFoundation\/AVFoundation.h&gt;<\/p>\n<p>[\/code]<\/p>\n<p>Add the following two variables, and four UIButtons in your viewController;<\/p>\n<p>[code lang=&#8221;objc&#8221;]<br \/>\n\/\/for recording section<br \/>\nAVAudioRecorder *audioRecorder;<br \/>\nIBOutlet UIButton *recordingButton;<br \/>\nIBOutlet UIButton *stopRecordingButton;<br \/>\n\/\/for playback section<br \/>\nAVAudioPlayer *audioPlayer;<br \/>\nIBOutlet UIButton *playButton;<br \/>\nIBOutlet UIButton *stopPlayingButton;<br \/>\n[\/code]<\/p>\n<p>The name of variables are enough to describe their usage in our program; Bind the outlets with respective buttons on xib file;<\/p>\n<p>Now add following methods in your .h file<\/p>\n<p>[code lang=&#8221;objc&#8221;]<br \/>\n-(IBAction) recordAudio;<br \/>\n-(IBAction) stopRecording;<br \/>\n-(IBAction) playAudio;<br \/>\n-(IBAction) stopPlaying;<br \/>\n[\/code]<\/p>\n<h3><strong>4. Your .m file, actual code<\/strong><\/h3>\n<p>Add the following code in your viewDidLoad method<\/p>\n<p>[code lang=&#8221;objc&#8221; wraplines=&#8221;false&#8221;]<br \/>\n&#8211; (void)viewDidLoad {<br \/>\n[super viewDidLoad];<br \/>\naudioRecorder.delegate = self;<br \/>\naudioPlayer.delegate = self;<br \/>\nplayButton.enabled = NO;<br \/>\nstopPlayingButton.enabled = NO;<br \/>\nNSArray *dirPaths;<br \/>\nNSString *docsDir;<br \/>\ndirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);<br \/>\ndocsDir = [dirPaths objectAtIndex:0];<br \/>\nNSString *soundFilePath = [docsDir stringByAppendingPathComponent:@&#8221;sound.caf&#8221;];<br \/>\nNSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];<br \/>\nNSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:<br \/>\n[NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,<br \/>\n[NSNumber numberWithInt:16], AVEncoderBitRateKey,<br \/>\n[NSNumber numberWithInt: 2], AVNumberOfChannelsKey,<br \/>\n[NSNumber numberWithFloat:44100.0], AVSampleRateKey,<br \/>\nnil];<br \/>\nNSError *error = nil;<br \/>\naudioRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL<br \/>\nsettings:recordSettings<br \/>\nerror:&amp;error];<br \/>\nif (error){<br \/>\nNSLog(@&#8221;error: %@&#8221;, [error localizedDescription]);<br \/>\n} else {<br \/>\n[audioRecorder prepareToRecord];<br \/>\n}<br \/>\n}<br \/>\n[\/code]<\/p>\n<p>Now add the action methods, bind with each UIButton over screen;<\/p>\n<p>[code lang=&#8221;objc&#8221; wraplines=&#8221;false&#8221;]<br \/>\n-(IBAction) recordAudio{<br \/>\nif (!audioRecorder.recording){<br \/>\nplayButton.enabled = NO;<br \/>\nstopRecordingButton.enabled = YES;<br \/>\n[audioRecorder record];<br \/>\n}<br \/>\n}<br \/>\n\/\/&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\n-(IBAction)stopRecording{<br \/>\nstopRecordingButton.enabled = NO;<br \/>\nplayButton.enabled = YES;<br \/>\nrecordingButton.enabled = YES;<br \/>\nif (audioRecorder.recording){<br \/>\n[audioRecorder stop];<br \/>\n}<br \/>\n}<br \/>\n\/\/&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\n-(IBAction) stopPlaying{<br \/>\nif (audioPlayer.playing) {<br \/>\n[audioPlayer stop];<br \/>\n}<br \/>\n}<br \/>\n\/\/&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\n-(IBAction) playAudio{<br \/>\nif (!audioRecorder.recording){<br \/>\nstopPlayingButton.enabled = YES;<br \/>\nrecordingButton.enabled = NO;<br \/>\nNSError *error;<br \/>\naudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioRecorder.url error:&amp;error];<br \/>\naudioPlayer.delegate = self;<br \/>\nif (error)<br \/>\nNSLog(@&#8221;Error: %@&#8221;, [error localizedDescription]);<br \/>\nelse<br \/>\n[audioPlayer play];<br \/>\n}<br \/>\n}<br \/>\n[\/code]<\/p>\n<p>You can also implement these delegate methods, though to keep the tutorial simple, I&#8217;m not using them wisely here;<\/p>\n<p>[code lang=&#8221;objc&#8221; wraplines=&#8221;false&#8221;]<\/p>\n<p>-(void)audioPlayerDidFinishPlaying: (AVAudioPlayer *)player successfully:(BOOL)flag{<br \/>\nrecordingButton.enabled = YES;<br \/>\nstopPlayingButton.enabled = NO;<br \/>\n}<br \/>\n\/\/&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\n-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{<br \/>\nNSLog(@&#8221;Decode Error occurred&#8221;);<br \/>\n}<br \/>\n\/\/&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\n-(void)audioRecorderDidFinishRecording: (AVAudioRecorder *)recorder successfully:(BOOL)flag{<br \/>\nNSLog(@&#8221;Audio Player has finished recording&#8221;);<br \/>\n}<br \/>\n\/\/&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\n-(void)audioRecorderEncodeErrorDidOccur: (AVAudioRecorder *)recorder error:(NSError *)error{<br \/>\nNSLog(@&#8221;Encode Error occurred&#8221;);<br \/>\n}<br \/>\n\/\/&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<\/p>\n<p>[\/code]<\/p>\n<p>And we are good to go now; Just run the code, tap Record in recording section and speak something in your microphone; Hit stop and press Play in playback section; You&#8217;ll hear yourself for sure;<\/p>\n<p>The audio file has saved in \/Document\u00a0directory\u00a0of your project, and you can get its content by following code, for further uses;<\/p>\n<p>[code lang=&#8221;objc&#8221; wraplines=&#8221;false&#8221;]<br \/>\nNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);<br \/>\nNSString *documentsDirectory = [paths objectAtIndex:0];<br \/>\nNSString *filePath = [documentsDirectory stringByAppendingPathComponent:&lt;your_file_name&gt;];<br \/>\nNSData *fileContents = [NSData dataWithContentsOfFile:filePath];<br \/>\n[\/code]<\/p>\n<p>Thats it; You have done infact;<\/p>\n<p>Now its time to look some new concepts; Back to code when we initialized our AVAudioRecorder instance, we provide it a dictionary of setting, as given below<\/p>\n<p>[code lang=&#8221;objc&#8221; wraplines=&#8221;false&#8221;]<br \/>\nNSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:<br \/>\n[NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,<br \/>\n[NSNumber numberWithInt:16], AVEncoderBitRateKey,<br \/>\n[NSNumber numberWithInt: 2], AVNumberOfChannelsKey,<br \/>\n[NSNumber numberWithFloat:44100.0], AVSampleRateKey,<br \/>\nnil];<br \/>\nNSError *error = nil;<br \/>\naudioRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL settings:recordSettings error:&amp;error];<br \/>\n[\/code]<\/p>\n<p>This dictionary is holding the different parameters for the audio we are going to capture and record; It inclues Bit rate, Sample rate, Number of channels etc; Let discuss them one by one in a concise way;<\/p>\n<p><strong>Bit Rate<\/strong><br \/>\nBitrate refers to the number of bits\u2014or the amount of data\u2014that are processed over a certain amount of time; In audio, this usually means kilobits per second; For example, if you have a song with bitrate of 256 kilobits per second, meaning there are 256 kilobits of data stored in every second of a song; Multiply the bitrate with length of your song and you&#8217;ll get the file size; The higher the bitrate of a track, the more space it will take up on your computer;<\/p>\n<p><strong>Audio Channel<\/strong><br \/>\nA channel in audio is just one separate stream of audio information; Mono audio sources have one channel, Stereo sources have two (left and right), or in more simple words Mono is 1 audio channel (You hear the same sound in both ears) where as Stereo is 2 audio channels (Each headphone can hear a different sound)<br \/>\nNow a days, the normally 5.1 audio channel are being use, having five normal audio channels (Left, Center, Right, Left Surround, Right Surround)<\/p>\n<p><strong>Sample Rate<\/strong><br \/>\nSample rate is the number of samples of audio carried per second; In simple words it is a frequency of audio; Data equal to bit rate is passed to processor to generate sample rates (audio frequency); More sample rate means more frequency and hence more clear, smooth audio listening experience;<br \/>\n44.1 kHz is the sampling rate of audio CDs giving a 20 kHz maximum frequency; 20 kHz is the highest frequency generally audible by humans, so making 44.1 kHz the logical choice for most audio material.<\/p>\n<p>Read the code again for initializing the AVAudioRecorder instance; Hope this time you&#8217;ll have better understanding;<\/p>\n<p>Happy coding; (:<\/p>\n<p><img decoding=\"async\" src=\"http:\/\/s05.flagcounter.com\/count\/16wq\/bg_FFFFFF\/txt_000000\/border_FFFFFF\/columns_6\/maxflags_250\/viewers_0\/labels_0\/pageviews_1\/flags_1\/\" alt=\"Flag Counter\" border=\"0\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello dev mate; Hope you had a good weekend and refreshing Monday; Today we&#8217;ll learn how to record audio in iOS application; Now a days, I&#8217;m working on an application where I need to record voice of user for some processing; I tried some framework classes from iOS sdk in&#8230;<\/p>\n","protected":false},"author":1,"featured_media":4551,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[178,179,180,507,554,1076,1117],"class_list":["post-3525","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ios","tag-avaudioplayer","tag-avaudiorecorder","tag-avfoundation","tag-how-to-recored-audio-in-iphone","tag-iphone","tag-voice-recording","tag-xcode"],"_links":{"self":[{"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/posts\/3525","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/comments?post=3525"}],"version-history":[{"count":2,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/posts\/3525\/revisions"}],"predecessor-version":[{"id":4552,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/posts\/3525\/revisions\/4552"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/media\/4551"}],"wp:attachment":[{"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/media?parent=3525"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/categories?post=3525"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/tags?post=3525"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}