首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将AVAudioFile保存到文档目录?

如何将AVAudioFile保存到文档目录?
EN

Stack Overflow用户
提问于 2016-08-23 17:14:22
回答 2查看 1K关注 0票数 2

我想用NSDictionaryAVAudioFile保存到document目录。有谁可以帮我?

代码语言:javascript
复制
AVAudioFile *audiofile=[[AVAudioFile alloc] initForWriting:destinationURL settings:settings error:&error];

将此音频文件保存到文档目录...

EN

回答 2

Stack Overflow用户

发布于 2016-08-23 18:48:56

文档目录的路径:

代码语言:javascript
复制
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

将音频文件保存到documents目录:

代码语言:javascript
复制
BOOL status = [NSDictionary writeToFile:filePath atomically:YES];
if(status){
NSLog(@"File write successfully");
}
票数 0
EN

Stack Overflow用户

发布于 2016-08-23 19:21:09

代码语言:javascript
复制
- (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"];
}

它以文档的形式保存在下面

23Aug16_044104PM.aif

为什么我们保存上面的,是因为我们可以通过time.So区分前一个,下一个,我们现在不能混淆。

ViewController.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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

刚才我在iPhone 4s上尝试了下面的代码,它工作得很好。

AudioViewController.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39097085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档