Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 404 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I record audio on iPhone with AVAudioRecorder?

#11
for wav format below audio setting


NSDictionary *audioSetting = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:44100.0],AVSampleRateKey,
[NSNumber numberWithInt:2],AVNumberOfChannelsKey,
[NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
[NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
[NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey,
[NSNumber numberWithBool:0], AVLinearPCMIsBigEndianKey,
[NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
[NSData data], AVChannelLayoutKey, nil];


ref:

[To see links please register here]

Reply

#12
Great Thanks to **@Massimo Cafaro** and **Shaybc**
I was able achieve below tasks

***in iOS 8 :***

> **Record audio & Save**
>
> **Play Saved Recording**

1.Add "AVFoundation.framework" to your project

in .h file

2.Add below import statement 'AVFoundation/AVFoundation.h'.

3.Define "AVAudioRecorderDelegate"

4.Create a layout with Record, Play buttons and their action methids

5.Define Recorder and Player etc.

Here is the complete example code which may help you.

> ViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController <AVAudioRecorderDelegate>

@property(nonatomic,strong) AVAudioRecorder *recorder;
@property(nonatomic,strong) NSMutableDictionary *recorderSettings;
@property(nonatomic,strong) NSString *recorderFilePath;
@property(nonatomic,strong) AVAudioPlayer *audioPlayer;
@property(nonatomic,strong) NSString *audioFileName;

- (IBAction)startRecording:(id)sender;
- (IBAction)stopRecording:(id)sender;

- (IBAction)startPlaying:(id)sender;
- (IBAction)stopPlaying:(id)sender;

@end

Then do the job in

> ViewController.m

#import "ViewController.h"

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

@interface ViewController ()
@end

@implementation ViewController

@synthesize recorder,recorderSettings,recorderFilePath;
@synthesize audioPlayer,audioFileName;


#pragma mark - View Controller Life cycle methods
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}


#pragma mark - Audio Recording
- (IBAction)startRecording:(id)sender
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err)
{
NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err)
{
NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
return;
}

recorderSettings = [[NSMutableDictionary alloc] init];
[recorderSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recorderSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recorderSettings setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
[recorderSettings setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];

// Create a new audio file
audioFileName = @"recordingTestFile";
recorderFilePath = [NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName] ;

NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&err];
if(!recorder){
NSLog(@"recorder: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning" message: [err localizedDescription] delegate: nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
return;
}

//prepare to record
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;

BOOL audioHWAvailable = audioSession.inputIsAvailable;
if (! audioHWAvailable) {
UIAlertView *cantRecordAlert =
[[UIAlertView alloc] initWithTitle: @"Warning"message: @"Audio input hardware not available"
delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[cantRecordAlert show];
return;
}

// start recording
[recorder recordForDuration:(NSTimeInterval) 60];//Maximum recording time : 60 seconds default
NSLog(@"Recroding Started");
}

- (IBAction)stopRecording:(id)sender
{
[recorder stop];
NSLog(@"Recording Stopped");
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{
NSLog (@"audioRecorderDidFinishRecording:successfully:");
}


#pragma mark - Audio Playing
- (IBAction)startPlaying:(id)sender
{
NSLog(@"playRecording");

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
[audioPlayer play];
NSLog(@"playing");
}
- (IBAction)stopPlaying:(id)sender
{
[audioPlayer stop];
NSLog(@"stopped");
}

@end


![enter image description here][1]


[1]:
Reply

#13
-(void)viewDidLoad {
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];

}

- (IBAction)btnRecordDidClicked:(UIButton *)sender {
if (player1.playing) {
[player1 stop];
}

if (!recorder.recording) {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];

// Start recording
[recorder record];
[_recordTapped setTitle:@"Pause" forState:UIControlStateNormal];

} else {

// Pause recording
[recorder pause];
[_recordTapped setTitle:@"Record" forState:UIControlStateNormal];
}

[_stopTapped setEnabled:YES];
[_playTapped setEnabled:NO];

}

- (IBAction)btnPlayDidClicked:(UIButton *)sender {
if (!recorder.recording){
player1 = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
[player1 setDelegate:self];
[player1 play];
}
}

- (IBAction)btnStopDidClicked:(UIButton *)sender {
[recorder stop];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setActive:NO error:nil];
}

- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{
[_recordTapped setTitle:@"play" forState:UIControlStateNormal];

[_stopTapped setEnabled:NO];
[_playTapped setEnabled:YES];

}
Reply

#14
As per the above answers, I made some changes and I got the correct output.

**Step 1:** Under "inf.plist" add the Microphone usage permissions ==>


<key>NSMicrophoneUsageDescription</key>
<string>${PRODUCT_NAME} Microphone Usage</string>

**Step 2:**

1. Save record audio file into Local Document Directory

2. Play/Stop recording
3. Get the Duration of Saved audio file

Here is the source code. Please have a look at once and use it.

**ViewController.h**

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController{
AVAudioPlayer *audioPlayer;
AVAudioRecorder *audioRecorder;
}

-(IBAction) startRecording;
-(IBAction) stopRecording;
-(IBAction) playRecording;
-(IBAction) stopPlaying;

@end

**ViewController.m**

#import "ViewController.h"
@interface ViewController () <AVAudioRecorderDelegate, AVAudioPlayerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

-(IBAction) startRecording{
// Setup audio session
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err)
{
NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err)
{
NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
return;
}
AVAudioSessionRecordPermission permissionStatus = [audioSession recordPermission];
switch (permissionStatus) {
case AVAudioSessionRecordPermissionUndetermined:{
[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
// CALL YOUR METHOD HERE - as this assumes being called only once from user interacting with permission alert!
if (granted) {
// Microphone enabled code
NSLog(@"Mic permission granted. Call method for granted stuff.");
[self startRecordingAudioSound];
}
else {
// Microphone disabled code
NSLog(@"Mic permission indeterminate. Call method for indeterminate stuff.");
// UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
}];
break;
}
case AVAudioSessionRecordPermissionDenied:
// direct to settings...
NSLog(@"Mic permission denied. Call method for denied stuff.");

break;
case AVAudioSessionRecordPermissionGranted:
// mic access ok...
NSLog(@"Mic permission granted. Call method for granted stuff.");
[self startRecordingAudioSound];
break;
default:
// this should not happen.. maybe throw an exception.
break;
}
}

#pragma mark - Audio Recording
- (BOOL)startRecordingAudioSound{
NSError *error = nil;
NSMutableDictionary *recorderSettings = [[NSMutableDictionary alloc] init];
[recorderSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recorderSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recorderSettings setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
[recorderSettings setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];

// Create a new audio file
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath_ = [searchPaths objectAtIndex: 0];
NSString *pathToSave = [documentPath_ stringByAppendingPathComponent:[self dateString]];
NSLog(@"the path is %@",pathToSave);

// File URL
NSURL *url = [NSURL fileURLWithPath:pathToSave];//FILEPATH];

//Save recording path to preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setURL:url forKey:@"Test1"];
[prefs synchronize];

audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&error];
if (!audioRecorder)
{
NSLog(@"Error establishing recorder: %@", error.localizedFailureReason);
return NO;
}

// Initialize degate, metering, etc.
audioRecorder.delegate = self;
audioRecorder.meteringEnabled = YES;
//self.title = @"0:00";

if (![audioRecorder prepareToRecord])
{
NSLog(@"Error: Prepare to record failed");
//[self say:@"Error while preparing recording"];
return NO;
}

if (![audioRecorder record])
{
NSLog(@"Error: Record failed");
// [self say:@"Error while attempting to record audio"];
return NO;
}
NSLog(@"Recroding Started");
return YES;
}

#pragma mark - AVAudioRecorderDelegate
- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{
NSLog (@"audioRecorderDidFinishRecording:successfully:");
}

#pragma mark - AVAudioPlayerDelegate
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog (@"audioPlayerDidFinishPlaying:successfully:");
}

- (NSString *) dateString {
// return a formatted string for a file name
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"ddMMMYY_hhmmssa";
return [[formatter stringFromDate:[NSDate date]]stringByAppendingString:@".aif"];
}

-(IBAction) stopRecording{
NSLog(@"stopRecording");
[audioRecorder stop];
NSLog(@"stopped");
}

-(IBAction) playRecording{
//Load recording path from preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSURL *temporaryRecFile = [prefs URLForKey:@"Test1"];

//Get Duration of Audio File
AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:temporaryRecFile options:nil];
CMTime audioDuration = audioAsset.duration;
float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
NSLog(@"Duration Of Audio: %f", audioDurationSeconds);

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
audioPlayer.volume = 1;
[audioPlayer prepareToPlay];
[audioPlayer play];
NSLog(@"playing");
}

-(IBAction) stopPlaying{
NSLog(@"stopPlaying");
[audioPlayer stop];
NSLog(@"stopped");
}

@end
Reply

#15
These answers are all in Objective-C, here is an answer in **Swift**. The only thing not included here are the pList [Microphone Permissions][1] that are necessary to allow recording.

The steps are laid out in 17 comments

class ViewController: UIViewController {

var arrOfRecordingUrls: [URL]() // 0. this is for the recordings once you stop recording in step 15. What you do with the recordings afterwards is up to to you.

var micRecorder: AVAudioRecorder? // 1. AVAudioRecorder instance that you will initialize every time you start to record in step 6

override func viewDidLoad() {
super.viewDidLoad()

// 2. set the AudioSession - you should make sure that the user has accepted the microphone permissions in your info.pList sometime before this
do {
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: .defaultToSpeaker)
try AVAudioSession.sharedInstance().setActive(true)

} catch {
print(error.debugDescription)
}
}

// 3. recordButton - if the micRecorder is nil start a recording, if not then a recording is currently taking place so stop it
@IBAction func recordButtonTapped(_ sender: Any) {

if micRecorder == nil {

startMicRecording()

} else {

stopMicRecording()
}
}

// *** if the pList Mic Permissions aren't granted then this won't work ***
func startMicRecording() {

// 4. create audioSettings
let myAudioSettings: [String:Any] = [AVFormatIDKey: kAudioFormatMPEG4AAC,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 44100.0,
AVEncoderBitRateKey: 64000,
AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue
]

// 5. create a file/url which will be where the recording is stored
let dirPath = "\(NSTemporaryDirectory())_Recordings_\(UUID().uuidString).m4a"
let fileURL = URL(fileURLWithPath: dirPath)

do {

// 6. initialize the micRecorder with the audio settings from step 4. and the file/url from step 5
micRecorder = try AVAudioRecorder(url: fileURL, settings: myAudioSettings)

micRecorder?.prepareToRecord() // 7. prepare the micRecorder

micRecorder?.delegate = self // 8. set the delegate so that you can access the recording file/url from step 5 once you are done

micRecorder?.isMeteringEnabled = true // optional

micRecorder?.record() // 9. call .record() to start recording

} catch {
print(error.localizedDescription)
}
}

func stopMicRecording() {

micRecorder?.stop() // 10. call .stop() to stop the recording. At this point the delegate methods from step 12/13/17 will be where the recording output (file/url from step 5) will end up

micRecorder = nil // 11. set the micRecorder to nil
}
}

// 12. set the AVAudioRecorderDelegate which is the .delegate = self from step 8
extension ViewController: AVAudioRecorderDelegate {

// your recording should end up here
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {

// 13. if the recording was successful this flag will be true
if flag {

// 14. the file/url from step 5 which is the recording
let successfullyRecordedURL = recorder.url

// 15. add the file/url to the array from step 0.
arrOfRecordingUrls.append(successfullyRecordedURL)

} else {

// 16. the flag was false something went wrong with the recording ???
}
}

// 17. if an error occurs while encoding it will be reported to the delegate
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {

guard let error = error else { return }
print(error.localizedDescription)
}
}


[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through