Objective c 在iPhone中录制后如何保存音频文件?

Objective c 在iPhone中录制后如何保存音频文件?,objective-c,audio-recording,Objective C,Audio Recording,嗨,我有记录剂量的代码,但我不知道如何保存,当我再次回来时,我可以再次播放相同的记录文件吗 我正在使用以下代码进行记录- ----- -(IBAction) startRecording { NSLog(@"startRecording"); [audioRecorder release]; audioRecorder = nil; // Init audio with record capability AVAudioSession *audioSes

嗨,我有记录剂量的代码,但我不知道如何保存,当我再次回来时,我可以再次播放相同的记录文件吗

我正在使用以下代码进行记录-

-----
-(IBAction) startRecording
{
    NSLog(@"startRecording");
    [audioRecorder release];
    audioRecorder = nil;

    // Init audio with record capability
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];

    NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc]                 initWithCapacity:10];
    if(recordEncoding == ENC_PCM)
    {
        [recordSettings setObject:[NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey];
        [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey];
    [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
    [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];   
    } else {
    NSNumber *formatObject;

    switch (recordEncoding) {
    case (ENC_AAC): 
        formatObject = [NSNumber numberWithInt: kAudioFormatMPEG4AAC];
        break;
    case (ENC_ALAC):
        formatObject = [NSNumber numberWithInt: kAudioFormatAppleLossless];
        break;
    case (ENC_IMA4):
        formatObject = [NSNumber numberWithInt: kAudioFormatAppleIMA4];
        break;
    case (ENC_ILBC):
        formatObject = [NSNumber numberWithInt: kAudioFormatiLBC];
        break;
    case (ENC_ULAW):
        formatObject = [NSNumber numberWithInt: kAudioFormatULaw];
        break;
    default:
        formatObject = [NSNumber numberWithInt: kAudioFormatAppleIMA4];
}

[recordSettings setObject:formatObject forKey: AVFormatIDKey];
[recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey];
[recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
[recordSettings setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];
[recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSettings setObject:[NSNumber numberWithInt: AVAudioQualityHigh] forKey: AVEncoderAudioQualityKey];
}

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", [[NSBundle mainBundle] resourcePath]]];


NSError *error = nil;
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];

if ([audioRecorder prepareToRecord] == YES){
    [audioRecorder record];
} else {
    int errorCode = CFSwapInt32HostToBig ([error code]); 
    NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode); 

}
NSLog(@"recording");
}
----
请让我知道如何保存此音频文件?所以我可以再次打开应用程序并播放录制的文件


谢谢

为要保存的文件名附加一个有效路径。例如,获取应用程序文档目录的可写路径:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
NSString *recordDir = [paths objectAtIndex:0];
将此
recordDir
附加到文件名:

NSString *recordFile = [recordDir stringByAppendingPathComponent: @"recordTest.caf"];
使用此完整路径获取以下内容的url:

NSURL *url = [NSURL fileURLWithPath:recordFile];

现在使用此url在ViewController中创建一个
AVAudioRecorder

已清理的viewLoad。m:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

NSArray *documentsFolders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[documentsFolders objectAtIndex:0] stringByAppendingPathComponent:@"Recording.aiff"];

[library writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:path] completionBlock:^(NSURL *assetURL, NSError *error){

    /*notify of completion*/

    NSLog(@"AssetURL: %@",assetURL);
    NSLog(@"Error: %@",error);

    if (!error) {
        //video saved

        [[self appDelegate] showAlertWithTitle:@"Audio Saved" message:@""];

    }
    else{

        [[self appDelegate] showAlertWithTitle:@"Error" message:error.domain];

    }

}];
-(无效)viewDidLoad {

在ViewController.m中编辑的记录:

- (IBAction) record
{

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

// 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];
}
在ViewController中编辑播放。m:

-(IBAction)playBack
 {

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


}
- (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"];
}
并向ViewController.m添加了一个新的dateString方法:

-(IBAction)playBack
 {

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


}
- (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"];
}
现在,它可以通过NSUserdefaults加载上一个录制的文件,加载时使用:

//Load recording path from preferences
  NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];


  temporaryRecFile = [prefs URLForKey:@"Test1"];



  player = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];
in(iAction)playBack.temporaryRecFile是我的ViewController类中的NSURL变量

声明为以下ViewController.h:

 @interface SoundRecViewController : UIViewController <AVAudioSessionDelegate,AVAudioRecorderDelegate, AVAudioPlayerDelegate>
{
 ......
 ......
NSURL *temporaryRecFile;

AVAudioRecorder *recorder;
AVAudioPlayer *player;

 }
 ......
 ......
  @end
@界面SoundRecViewController:UIViewController
{
......
......
NSURL*临时记录文件;
AVAudioRecorder*录音机;
AVAudioPlayer*播放器;
}
......
......
@结束