2

我想AVAudioFileNSDictionary. 谁能帮我?

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

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

4

2 回答 2

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

它在下面保存为文档

23Aug16_044104PM.aif

为什么我们在上面保存是因为我们可以按时间区分上一个下一个。所以我们现在不能混淆。

视图控制器.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

视图控制器.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];
 }

永久录制和保存音频

录制音频文件并保存在本地

刚才我用 iPhone 4s 尝试了下面的代码,它运行良好。

音频视图控制器.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

音频视图控制器.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

这里是源

于 2016-08-23T11:21:08.827 回答
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");
}
于 2016-08-23T10:48:55.563 回答