IOS recording practices

Source: Internet
Author: User
Tags file url

IOS recording practices

In the AVFoundation framework, the AVAudioRecorder class specializes in recording operations and supports multiple audio formats. The following are common attributes and methods:

 

Attribute Description
@ Property (readonly, getter = isRecording) BOOL recording; Recording in progress, read-only
@ Property (readonly) NSURL * url Recording file address, read-only
@ Property (readonly) NSDictionary * settings Recording File Settings, read-only
@ Property (readonly) NSTimeInterval currentTime Recording duration, read-only, note that only the recording status is available
@ Property (readonly) NSTimeInterval deviceCurrentTime Enter the set length of time. Read-Only. Note that this attribute is always accessible.
@ Property (getter = isMeteringEnabled) BOOL meteringEnabled; Whether to enable recording measurement. If recording measurement is enabled, data information such as recording decibels can be obtained.
@ Property (nonatomic, copy) NSArray * channelAssignments Current recording Channel
Object Method Description
-(Instancetype) initWithURL :( NSURL *) url settings :( NSDictionary *) settings error :( NSError **) outError The recorder object initialization method. Note that the url must be a local file url, and the settings are the recording format, encoding, and other settings.
-(BOOL) prepareToRecord Prepare the recording, which is mainly used to create a buffer. If it is not manually called, it is automatically called when the record recording is called.
-(BOOL) record Start recording
-(BOOL) recordAtTime :( NSTimeInterval) time Recording starts at the specified time. It is generally used to pause recording and resume recording.
-(BOOL) recordForDuration :( NSTimeInterval) duration Start recording Based on the specified duration
-(BOOL) recordAtTime :( NSTimeInterval) time forDuration :( NSTimeInterval) duration Start recording at the specified time and specify the recording duration
-(Void) pause; Pause recording
-(Void) stop; Stop recording
-(BOOL) deleteRecording; Delete the recording. Note that the recording recorder must be stopped at this time.
-(Void) updateMeters; Update measurement data. Note that this method is only available when meteringEnabled is YES.
-(Float) peakPowerForChannel :( NSUInteger) channelNumber; The measurement peak value of the specified channel. Note that the value is available only after updateMeters is called.
-(Float) averagePowerForChannel :( NSUInteger) channelNumber The average measurement value of the specified channel. Note that the value is available only after updateMeters is called.
Proxy Method Description
-(Void) audioRecorderDidFinishRecording :( AVAudioRecorder *) recorder successfully :( BOOL) flag Complete recording
-(Void) audioRecorderEncodeErrorDidOccur :( AVAudioRecorder *) recorder error :( NSError *) error Recording Encoding Error

 

 

When creating a recorder, AVAudioRecorder must specify the recording settings in addition to the specified path, because the recorder must know the format, sampling rate, number of channels, and number of digits at each sampling point, usually only a few common settings are required. For more information about recording Settings, see "AV Foundation Audio Settings Constants" in the help document ".

The following code enables recording, pause, continue, cancel, stop, and play.

 

# Import ViewController. h # import # define kAudioFileName @ test. caf @ interface ViewController () @ property (nonatomic, strong) AVAudioRecorder * audioRecorder; // Audio Recorder @ property (nonatomic, strong) AVAudioPlayer * audioPlayer; // audio player @ property (nonatomic, strong) NSTimer * timer; // recording monitoring @ property (weak, nonatomic) IBOutlet UIProgressView * audioPower; @ end @ implementation ViewController-(void) viewDidLoad {[super ViewDidLoad]; [self setAudioSession];}-(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} /*** set the audio session */-(void) setAudioSession {AVAudioSession * audioSession = [AVAudioSession sharedInstance]; // set it to the playing and recording status, this allows you to play the recording after recording [audioSession setCategory: AVAudioSessionCategoryPlayAndRecord error: nil]; [audioSession setActive: YES error: nil];} /*** Recording File Settings ** @ return recording settings */-(NSDictionary *) getAudioSetting {NSMutableDictionary * dic = [NSMutableDictionary dictionary]; [dic setObject: @ (kAudioFormatLinearPCM) forKey: AVFormatIDKey]; // set the recording format [dic setObject: @ (8000) forKey: AVSampleRateKey]; // set the sampling rate [dic setObject: @ (1) forKey: AVNumberOfChannelsKey]; // set the channel. Here, the single channel [dic setObject: @ (8) forKey: AVLinearPCMBitDepthKey] is used; // The number of digits of each sampling point, which can be 8 to 16, 24, and 32 [Dic setObject: @ (YES) forKey: AVLinearPCMIsFloatKey]; // whether to use floating point sampling return dic ;} /*** recording storage path ** @ return storage path */-(NSURL *) getSavePath {NSString * url = [NSSearchPathForDirectoriesInDomains (NSDocumentationDirectory, NSUserDomainMask, YES) lastObject]; url = [url stringByAppendingPathComponent: kAudioFileName]; return [NSURL URLWithString: url] ;}- (NSTimer *) timer {if (! _ Timer) {_ timer = [NSTimer scheduledTimerWithTimeInterval: 1 target: self selector: @ selector (audioPowerChange) userInfo: nil repeats: YES];} return _ timer ;} -(AVAudioRecorder *) audioRecorder {if (! _ AudioRecorder) {NSError * error = nil; _ audioRecorder = [[delealloc] initWithURL: [self getSavePath] settings: [self getAudioSetting] error: & error]; _ audioRecorder. delegate = self; _ audioRecorder. meteringEnabled = YES; // whether to enable recording measurement. if recording measurement is enabled, data information such as recording decibel can be obtained. if (error) {NSLog (@ error occurred when creating a recorder object: % @, error. localizedDescription); return nil;} return _ audioRecorder;}-(AVAudioPlayer *) audioPlayer {if (! _ AudioPlayer) {NSError * error = nil; _ audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [self getSavePath] error: & error]; if (error) {NSLog (@ error occurred when creating the Audio Player Object: % @, error. localizedDescription); return nil;} return _ audioPlayer;} # pragma mark-success // recording success-(void) Success :( AVAudioRecorder *) recorder successfully :( BOOL) flag {if (! [Self. audioPlayer isPlaying]) {[self. audioPlayer play] ;}}// recording failed-(void) audioRecorderEncodeErrorDidOccur :( AVAudioRecorder *) recorder error :( NSError *) error {}# pragma mark-# pragma mark-Action-(void) audioPowerChange {[self. audioRecorder updateMeters]; // update the measured value float power = [self. audioRecorder averagePowerForChannel: 1]; // obtain the audio of the first channel. Pay attention to the audio intensity range:-160 to 0 self. audioPower. SS = (1.0/160) * (power + 160 );}/*** Click the recording button ** @ param sender recording button */-(IBAction) startRecord :( id) sender {if (! [Self. audioRecorder isRecording]) {[self. audioRecorder record]; self. timer. fireDate = [NSDate distantPast] ;}}/*** click the cancel recording button ** @ param sender to cancel the recording button */-(IBAction) cancelRecord :( id) sender {self. audioRecorder. delegate = nil; if ([self. audioRecorder isRecording]) {[self. audioRecorder stop];} self. audioRecorder = nil;}/*** click the tentative button ** @ param sender pause button */-(IBAction) pause :( id) sender {if ([self. a UdioRecorder isRecording]) {[self. audioRecorder pause]; self. timer. fireDate = [NSDate distantFuture];}/*** click the restore button. * You only need to call record again to restore the recording, AVAudioSession will help you record the location of the last recording and append the recording ** @ param sender recovery button */-(IBAction) goon :( id) sender {[self startRecord: nil];} /*** click the stop button ** @ param sender stop button */-(IBAction) stop :( id) sender {if ([self. audioRecorder isRecording]) {[self. audioRecorder stop]; self. timer = [NS Date distantFuture] ;}}/*** click the play button ** @ param sender play button */-(IBAction) play :( id) sender {if (! [Self. audioPlayer isPlaying]) {[self. audioPlayer play] ;}}


 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.