2016-08-23 2 views
2

AVAudioFileNSDictionary과 함께 문서 디렉토리에 저장하고 싶습니다. 누구든지 나를 도울 수 있습니까?AVAudioFile을 문서 디렉토리에 저장하는 방법은 무엇입니까?

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

이 오디오 파일이 디렉토리에 문서 저장 ... 문서 디렉토리에

+0

이 링크를하시기 바랍니다 http://stackoverflow.com/questions/15059089/record-audio-and-save -permanently-in-ios –

+0

저장하는 방법? 이 문제는 다른 모든 것이 잘 어디 절약을 위해이 오디오 파일을 추가 할 수 있습니다 U에 대한 코드를 제공 할 수 있습니까 ??? –

+0

고마워요 형제하지만 내 "audiofile"을 추가 할 곳이 없다 –

답변

0

경로 :

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

문서 디렉토리에 오디오 파일 저장 :

BOOL status = [NSDictionary writeToFile:filePath atomically:YES]; 
if(status){ 
NSLog(@"File write successfully"); 
} 
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"]; 
} 

다음과 같이 저장합니다. 문서

우리는 위의 저장 우리는 우리가 혼동 할 수 time.So로 이전 한 다음 하나를 differenciate 수 있습니다 좋아하는 이유

23Aug16_044104PM.aif

있다.

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는

Record Audio File and save Locally

Record and Save Audio Permanently

#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]; 
} 
그냥 지금은 아이폰 4S와 아래의 코드를 시도하고 완벽하게 작동합니다.

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

+0

아니요. 작동하지 않습니다 ........ 나를 위해 내 AVAudioFile –

+0

내게 내가 제공하는 코드를 제공하는 오디오 파일을 AVAudioFile "AVAudioFile"에 저장 솔루션을 제공 할 수 있습니다 ... 나는 녹음 된 오디오의 피치를 변경하고 그 영향을 오디오 문서 디렉토리 :( –

+0

지금 내 대답을 확인하십시오.나는 나의 대답을 업데이트했다 – user3182143

관련 문제