The Avaudiorecorder__ios of IOS development

Source: Internet
Author: User
Tags file url

In the Avfoundation framework, a Avaudiorecorder class specifically handles recording operations, and it also supports multiple audio formats. Like Avaudioplayer, you can totally consider it a sound Recorder control class, and here are the common properties and methods:

Property Description
@property (readonly, getter=isrecording) BOOL recording; is recording, read only
@property (readonly) Nsurl *url Audio file address, read only
@property (readonly) nsdictionary *settings Audio file settings, read only
@property (readonly) Nstimeinterval currenttime Long recording, read only, note only in recording status available
@property (readonly) Nstimeinterval Devicecurrenttime Enter the length of time set, read-only, note that this property is always accessible
@property (getter=ismeteringenabled) BOOL meteringenabled; Whether recording measurements are enabled, and if recording measurements are enabled, data information such as recording decibels can be obtained
@property (nonatomic, copy) Nsarray *channelassignments Channel for current recording
Object methods Description
-(Instancetype) Initwithurl: (nsurl *) URL settings: (nsdictionary *) settings error: (NSERROR * *) outerror Audio Recorder Object Initialization method, note that the URL must be a local file url,settings is a recording format, encoding, and other settings
-(BOOL) Preparetorecord Prepares recordings, primarily for creating buffers that, if not called manually, are automatically invoked when a record recording is called
-(BOOL) record Start recording
-(BOOL) Recordattime: (nstimeinterval) time Start recording at a specified time, usually for recording pause and resume recording
-(BOOL) Recordforduration: (nstimeinterval) duration Start recording by the specified length of time
-(BOOL) Recordattime: (nstimeinterval) Time forduration: (nstimeinterval) duration Start recording at a specified time and specify length of recording
-(void) pause; Pause Recording
-(void) stop; Stop Recording
-(BOOL) deleterecording; Delete Recording, note that the recorder must be in a stop state when the recording is to be deleted
-(void) updatemeters; Update measurement data, note that this method is only available if meteringenabled is yes
-(float) Peakpowerforchannel: (Nsuinteger) channelnumber; Specify the measurement peak of the channel, note that only the call is finished updatemeters only value
-(float) Averagepowerforchannel: (Nsuinteger) channelnumber Specifies the measurement average of the channel, noting that only the call is finished updatemeters only the value
Proxy method Description
-(void) audiorecorderdidfinishrecording: (Avaudiorecorder *) Recorder successfully: (BOOL) flag Finish recording
-(void) Audiorecorderencodeerrordidoccur: (Avaudiorecorder *) Recorder error: (NSERROR *) error Recording coding error

Avaudiorecorder many properties and methods are similar to Avaudioplayer, but they are created differently, and you must specify recording settings when creating a tape recorder, since the recorder must know the format of the recording file, the sampling rate, the number of channels, Information such as the number of bits per sample point, but not all of the information must be set, usually with only a few common settings. For audio settings, see the "AV Foundation Audio settings Constants" in the Help documentation.

The following is the use of avaudiorecorder to create a recorder, recording, pause, stop, playback and other functions, achieve the effect is as follows:

In this example, a complete recording control will be implemented, including recording, pausing, resuming, stopping, and displaying the sound fluctuations of the user's recordings in real time, when the user clicks on the Stop button and automatically plays the recording file.  The construction of the program is mainly divided into the following steps: Set the audio session type to Avaudiosessioncategoryplayandrecord, because the program involves recording and playback operations.  Create a Sound Recorder avaudiorecorder, specify the path to save the recording and set the recording properties, note that for the general recording file requirements of the sampling rate, the number of digits is not high, need to be properly set to ensure the size and effect of the recording file. Set up the recorder agent to play the recording after the recording is complete, and turn on the recording to ensure that the sound intensity of the recording can be obtained in real time.  (Note that the sound intensity range-160 to 0, 0 represents the maximum input) creates an audio player Avaudioplayer to play the recording after the recording is complete.  Create a timer to refresh the recording measurements in real time and update the recording strength to display in Uiprogressview. Add recording, pause, resume, stop operation, need to pay attention to the recording of the recovery operation is actually audio session management, restore as long as the record method can be called again, no need to manually manage recovery time.

Here is the main code:

VIEWCONTROLLER.M//Avaudiorecorder////Created by Kenshin Cui on 14/03/30. Copyright (c) 2014 Cmjstudio.
All rights reserved. #import "ViewController.h" #import <AVFoundation/AVFoundation.h> #define Krecordaudiofile @ "MYRECORD.CAF" @ Interface Viewcontroller () <AVAudioRecorderDelegate> @property (nonatomic,strong) Avaudiorecorder * audiorecorder;//Audio Recorder @property (nonatomic,strong) Avaudioplayer *audioplayer;//Audio player for playback of the recording file @property (Nonatomic, Strong) Nstimer *timer;//recording Sound wave monitoring (note that the playback is temporarily not monitored) @property (weak, nonatomic) Iboutlet UIButton, *record;//start recording @property ( Weak, nonatomic) Iboutlet UIButton *pause;//suspend recording @property (weak, nonatomic) Iboutlet UIButton *resume;//Resume Recording @property (w Eak, nonatomic) iboutlet UIButton *stop;//stop recording @property (weak, nonatomic) Iboutlet Uiprogressview audio fluctuations @en
    
    D @implementation Viewcontroller #pragma mark-Controller view Method-(void) viewdidload {[Super viewdidload];
[Self setaudiosession]; } #pragma MarK-Private Method/** * Set audio session/-(void) setaudiosession{avaudiosession *audiosession=[avaudiosession sharedinstance];
    Set to playback and recording status so that you can play the recording after the recording [Audiosession Setcategory:avaudiosessioncategoryplayandrecord Error:nil];
[Audiosession Setactive:yes Error:nil]; /** * Obtain recording File save path * * @return Recording file path * * (Nsurl *) getsavepath{nsstring *urlstr=[nssearchpathfordirectoriesind
    Omains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject];
    Urlstr=[urlstr Stringbyappendingpathcomponent:krecordaudiofile];
    NSLog (@ "File path:%@", URLSTR);
    Nsurl *url=[nsurl FILEURLWITHPATH:URLSTR];
return URL; /** * Get audio File Settings * * @return Recording Settings * * * (nsdictionary *) getaudiosetting{nsmutabledictionary *dicm=[nsmutabledict
    Ionary dictionary];
    Set recording format [DICM setobject:@ (KAUDIOFORMATLINEARPCM) Forkey:avformatidkey];
    Set the recording sample rate, 8000 is the telephone sampling rate, for the general recording has been enough [DICM setobject:@ (8000) Forkey:avsampleratekey]; Set the channel, which uses mono [DICM setobject:@ (1) forkey:avnumberofchAnnelskey];
    Each sampling point number is divided into 8, 16, 24, and [DICM setobject:@ (8) Forkey:avlinearpcmbitdepthkey];
    Whether to use floating-point number sampling [DICM setobject:@ (YES) Forkey:avlinearpcmisfloatkey]; //....
Other settings such as return DICM; /** * Obtain audio Recorder Object * * @return Recorder Object * * (Avaudiorecorder *) audiorecorder{if (!_audiorecorder) {//Create audio file
        Save path Nsurl *url=[self Getsavepath];
        Create recording format settings Nsdictionary *setting=[self getaudiosetting];
        Create a recorder nserror *error=nil;
        _audiorecorder=[[avaudiorecorder Alloc]initwithurl:url settings:setting error:&error];
        _audiorecorder.delegate=self; _audiorecorder.meteringenabled=yes;//if you want to monitor sound waves, you must set to YES if (error) {NSLog (@ "Create a tape recorder object when errors occur, error message:%@", errors
            . localizeddescription);
        return nil;
} return _audiorecorder; /** * Create player * * @return player * * (Avaudioplayer *) audioplayer{if (!_audioplayer) {Nsurl *url=[self g
        Etsavepath]; Nserror *erroR=nil;
        _audioplayer=[[avaudioplayer Alloc]initwithcontentsofurl:url error:&error];
        _audioplayer.numberofloops=0;
        [_audioplayer Preparetoplay];
            Error {NSLOG (Error message:%@ ", error.localizeddescription) during the creation of the player in the if (error) {)
        return nil;
} return _audioplayer; /** * Recording Sonic Monitor Customizer * * @return Timer * * (Nstimer *) timer{if (!_timer) {_timer=[nstimer Scheduledtimerwi
    thtimeinterval:0.1f target:self selector: @selector (audiopowerchange) Userinfo:nil Repeats:yes];
return _timer; /** * Sound Recording acoustic state setting/-(void) audiopowerchange{[self.audiorecorder updatemeters];//Update measurement value float power= [Self.audi
    Orecorder averagepowerforchannel:0];//obtains the first channel audio, note the audio intensity range when-160 to 0 cgfloat progress= (1.0/160.0) * (power+160.0);
[Self.audiopower setprogress:progress]; #pragma mark-ui Event/** * Click the recording button * @param sender Recording Button * * * (ibaction) Recordclick: (UIButton *) Sender {if (![ Self.audiorecorder IsrecordiNG] {[Self.audiorecorder record];//First use the application when calling the record method asks the user if it is allowed to use the microphone self.timer.firedate=[nsdate distant
    Past]; /** * Click the tentative button * * @param sender pause button * * (ibaction) Pauseclick: (UIButton *) Sender {if ([Self.audiorecorder
        IsRecording]) {[Self.audiorecorder pause];
    Self.timer.firedate=[nsdate Distantfuture]; /** * Click the Restore button * Resume recording only need to call again record,avaudiosession will help you to record the last recording position and add the recording * * @param sender Restore Button * *-(Ibaction) resume

Click: (UIButton *) sender {[self recordclick:sender];}
    /** * Click the stop button * * @param sender Stop button * * (ibaction) Stopclick: (UIButton *) Sender {[Self.audiorecorder stop];
    Self.timer.firedate=[nsdate Distantfuture];
self.audiopower.progress=0.0; #pragma mark-Sound Recorder Agent Method/** * Recording completed, recording after completion of recording * * @param recorder Recorder Object * @param flag is successful/-(void) Audiorec Orderdidfinishrecording: (Avaudiorecorder *) Recorder successfully: (BOOL) flag{if (![ Self.audioplayer isplaying]) {[Self. Audioplayer Play];

} NSLog (@ "Recording complete!");} @end

Operation Effect:

This article turns from: http://www.cnblogs.com/kenshincui/p/4186022.html

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.