SoFunction
Updated on 2025-04-12

IOS development to realize recording function

Import framework:

#import <AVFoundation/>

Declare global variables:

@interface ViewController ()<AVAudioRecorderDelegate>
{
  AVAudioRecorder *audioRecorder;
}
@end


In ViewDidLoad:

 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
   = CGRectMake(100, 100, 100, 100);
  [button setTitle:@"TICK" forState:UIControlStateNormal];
   = [UIColor brownColor];
  [button addTarget:self action:@selector(startAudioRecoder:) forControlEvents:UIControlEventTouchUpInside];
  [ addSubview:button];

The trigger event of the button

- (void)startAudioRecoder:(UIButton *)sender{
   = !;
  if ( != YES) {
    [audioRecorder stop];
    return;
  }
  
  // The URL is the local URL. AVAudioRecorder requires a storage path  NSString *name = [NSString stringWithFormat:@"%",(int)[NSDate date].timeIntervalSince1970];
  
  NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:name];
  NSError *error;
  // Recorder Initialization  audioRecorder = [[AVAudioRecorder alloc]initWithURL:[NSURL fileURLWithPath:path] settings:@{AVNumberOfChannelsKey:@2,AVSampleRateKey:@44100,AVLinearPCMBitDepthKey:@32,AVEncoderAudioQualityKey:@(AVAudioQualityMax),AVEncoderBitRateKey:@128000} error:&amp;error];
  [audioRecorder prepareToRecord];
  [audioRecorder record];
   = self;
  /*
     Number of channels is usually two channels value 2
     Sampling rate Unit HZ is usually set to 44100, that is, 44.1k
     Bit rate 8 16 24 32
     Sound quality
        ① AVAudioQualityMin = 0, minimum quality
        ② AVAudioQualityLow = 0x20, relatively low quality
        ③ AVAudioQualityMedium = 0x40, the middle quality
        ④ AVAudioQualityHigh = 0x60, high quality
        ⑤ AVAudioQualityMax = 0x7F Best quality
     Audio coded bit rate Unit Kbps Transmission rate Generally set 128000, that is, 128kbps
   
    */
  
  
  
  NSLog(@"%@",path);

}

Proxy method:

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
  NSLog(@"Recording ends");
// File operation class NSFileManager *manger = [NSFileManager defaultManager];

  NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// Get all subfiles of the current file subpathsAtPath  NSArray *pathlList = [manger subpathsAtPath:path];

// Only recording files are required  NSMutableArray *audioPathList = [NSMutableArray array];
// traverse all sub-files in this folder  for (NSString *audioPath in pathlList) {
//Distinguish whether it is a recording file by comparing the extension name (extension ending) of the file    if ([ isEqualToString:@"aiff"]) {
// Put the filtered files into an array      [audioPathList addObject:audioPath];
    }
  }
  
  NSLog(@"%@",audioPathList);
  
}