2

I want to save AVAudioFile to document directory with NSDictionary. Can anyone help me?

AVAudioFile *audiofile=[[AVAudioFile alloc] initForWriting:destinationURL settings:settings error:&error];

save this audio file to document directory...

DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
Mitesh Varu
  • 246
  • 1
  • 14

2 Answers2

0

Path to the documents directory:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

Saving the audio file to the documents directory:

BOOL status = [NSDictionary writeToFile:filePath atomically:YES];
if(status){
NSLog(@"File write successfully");
}
Saurabh Jain
  • 1,688
  • 14
  • 28
0
- (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"];
}

It saves below as in Documents

23Aug16_044104PM.aif

Why we save above like is we can differenciate the previous one next one by time.So we can't confuse now.

ViewController.h

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

@interface ViewController : UIViewController<AVAudioSessionDelegate,AVAudioRecorderDelegate, AVAudioPlayerDelegate>
{

  NSURL *temporaryRecFile;
  AVAudioRecorder *recorder;
  AVAudioPlayer *player;
}

- (IBAction)actionRecordAudion:(id)sender;

- (IBAction)actionPlayAudio:(id)sender;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad 
{
 [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
 AVAudioSession *audioSession = [AVAudioSession sharedInstance];
 [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
 [audioSession setActive:YES error:nil];
 [recorder setDelegate:self];
}

- (IBAction)actionRecordAudion:(id)sender
{

  NSError *error;

  // Recording settings
  NSMutableDictionary *settings = [NSMutableDictionary dictionary];

  [settings setValue: [NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
  [settings setValue: [NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
  [settings setValue: [NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
  [settings setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
  [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
  [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
  [settings setValue:  [NSNumber numberWithInt: AVAudioQualityMax] forKey:AVEncoderAudioQualityKey];

  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];

  // Create recorder
  recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
  [recorder prepareToRecord];
  [recorder record];
}
- (IBAction)actionPlayAudio:(id)sender
{
  AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
  [audioSession setActive:YES error:nil];
  //Load recording path from preferences
  NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  temporaryRecFile = [prefs URLForKey:@"Test1"];
  player = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];
  player.delegate = self;
  [player setNumberOfLoops:0];
  player.volume = 1;
  [player prepareToPlay];
  [player play];
 }

Record and Save Audio Permanently

Record Audio File and save Locally

Just now I tried the below code with iPhone 4s and it works perfectly.

AudioViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface AudioViewController : UIViewController<AVAudioSessionDelegate,AVAudioRecorderDelegate,AVAudioPlayerDelegate>

- (IBAction)actionRecordAudio:(id)sender;
- (IBAction)actionPlayAudio:(id)sender;
- (IBAction)actionStopAudio:(id)sender;

@property (strong, nonatomic) AVAudioRecorder *audioRecorder;
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

@end

AudioViewController.m

#import "AudioViewController.h"

@interface AudioViewController ()

@end

@implementation AudioViewController

@synthesize audioPlayer,audioRecorder;


- (void)viewDidLoad
{
  [super viewDidLoad];
  // Do any additional setup after loading the view.

  NSArray *dirPaths;
  NSString *docsDir;

  dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  docsDir = dirPaths[0];
  NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"sound.caf"];
  NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

  NSDictionary *recordSettings = [NSDictionary
                                dictionaryWithObjectsAndKeys:
                                [NSNumber numberWithInt:AVAudioQualityMin],
                                AVEncoderAudioQualityKey,
                                [NSNumber numberWithInt:16],
                                AVEncoderBitRateKey,
                                [NSNumber numberWithInt: 2],
                                AVNumberOfChannelsKey,
                                [NSNumber numberWithFloat:44100.0],
                                AVSampleRateKey,
                                nil];

  NSError *error = nil;

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

  audioRecorder = [[AVAudioRecorder alloc]initWithURL:soundFileURL settings:recordSettings error:&error];
  if (error)
  {
     NSLog(@"error: %@", [error localizedDescription]);
  } 
  else {
    [audioRecorder prepareToRecord];
  }

 }

- (void)didReceiveMemoryWarning 
{
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}


- (IBAction)actionRecordAudio:(id)sender
{
  if (!audioRecorder.recording)
  {
   [audioRecorder record];
  }
}

- (IBAction)actionPlayAudio:(id)sender
{
   if (audioRecorder.recording)
   {
      NSError *error;
      audioPlayer = [[AVAudioPlayer alloc]
                    initWithContentsOfURL:audioRecorder.url
                    error:&error];

      audioPlayer.delegate = self;

      if (error)
         NSLog(@"Error: %@",
              [error localizedDescription]);
      else
        [audioPlayer play];
   }
 }

 - (IBAction)actionStopAudio:(id)sender
 {
   if (audioRecorder.recording)
   {
      [audioRecorder stop];
   } 
   else if (audioPlayer.playing) {
    [audioPlayer stop];
   }
 }

 -(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
 {

 }

 -(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
   NSLog(@"Decode Error occurred");
}

-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
}

-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
  NSLog(@"Encode Error occurred");
}
@end

Here is source

Community
  • 1
  • 1
user3182143
  • 9,459
  • 3
  • 32
  • 39
  • can u provide me the solution for saving "AVAudioFile" to document directory the code u provided is just for playing an audio which is recorded... i want to change the pitch of recorded audio and save that effected audio in document directory :( – Mitesh Varu Aug 23 '16 at 11:43
  • i want to change the the pitch after user complete recording and then press button for changing pitch to convert the voice to male female child etc according to its requirement.... this will also not work in my case.... – Mitesh Varu Aug 23 '16 at 12:04
  • If you want to do like that, you have to save audio file in db and fetch particular audio file and edit and save.It does successfully that. – user3182143 Aug 23 '16 at 12:16
  • I gave you perfect answer what you asked in your question brother. – user3182143 Aug 23 '16 at 12:17
  • but how to edit that audio file and change pitch accordingly that the problem brother :( you are not understanding my problem :( – Mitesh Varu Aug 23 '16 at 12:20
  • Your question is "How to save AVAudioFile to document directory"? – user3182143 Aug 23 '16 at 12:21
  • http://stackoverflow.com/questions/39080185/how-to-save-the-audio-recorded-with-pitch-changed?noredirect=1#comment65508550_39080185 open this link u will understand http://stackoverflow.com/questions/39052576/how-to-save-the-audio-with-changed-pitch-and-speed-ios – Mitesh Varu Aug 23 '16 at 12:22
  • Already I told you that create db and insert the audio files from document directory to SQLite or any other db and fetch it from the db and edit and save. – user3182143 Aug 23 '16 at 12:23