Audio playback and recording of iOS development

Source: Internet
Author: User
Tags file url

iOS audio playback can be divided into short audio playback (e.g., audio effects, etc.) and long audio playback (for example: music and other main audio). The former does not need to control the progress, cycle, etc., while the latter requires precise control. Playing these two audio in iOS is done using Audiotoolbox.frameworK and Avfoundation.framework respectively.

Short Audio Sound

Audiotoolbox.framework is a C-based framework that uses it to play the sound effect by registering short audio with the system sound service. The System Sound Service is a simple, low-level voice playback service, but it also has some limitations:

    • No longer than seconds in duration (play time less than 30s)

    • In linear PCM or IMA4 (IMA/ADPCM) format (data must be in PCM or IMA4 format)

    • Packaged in a .caf , .aif or file .wav (the audio file must be packaged as a. caf,.aif,.wav file)

The steps to play the sound using the system voice Service are as follows (encapsulated as a tool class for playing short audio):

+ (void) Initialize {//load all audio files//1. Traverse all the audio files of the Plane.bundleNsfilemanager *manage =[Nsfilemanager Defaultmanager]; //2. Obtained the path of the Plane.bundleNSString *planepath = [[NSBundle mainbundle] Pathforresource:@"Plane.bundle"Oftype:nil]; Nsarray*contents =[Manage Contentsofdirectoryatpath:planepath error:nil]; //3. Traverse the MP3 file inside to create the Systemsoundid;Nsmutabledictionary *SOUNDDICTM =[Nsmutabledictionary dictionary];  for(NSString *soundnameinchcontents) {        //the URL of the audioNSString *soundurlpath =[Planepath Stringbyappendingpathcomponent:soundname]; Nsurl*soundurl =[Nsurl Fileurlwithpath:soundurlpath];                Systemsoundid Soundid; //Create a soundAudioservicescreatesystemsoundid (__bridge cfurlref) Soundurl, &Soundid); Sounddictm[soundname]=@ (Soundid); } sounddict=SOUNDDICTM;}- (void) Playshortsoundwithname: (NSString *) Soundname {//Play SoundAudioservicesplaysystemsound ([Sounddict[soundname] unsignedintvalue]);}

Long audio playback (implemented using Avfoundation.framework's Avaudioplayer)

The use of Avaudioplayer is relatively simple:

    1. Initializes the Avaudioplayer object, which typically specifies a local file path.
    2. Sets the properties of the player, such as number of repetitions, volume, and so on.
    3. Call the play method to play.
Property Description
@property (readonly, getter=isplaying) BOOL playing Is playing, read-only
@property (readonly) Nsuinteger Numberofchannels Number of audio channels, read-only
@property (readonly) nstimeinterval duration Audio duration
@property (readonly) Nsurl *url Audio file path, read-only
@property (readonly) NSData *data Audio data, read-only
@property Float pan Stereo balance, if 1.0 is the full left channel, if 0.0 is the left and right channel balance, if 1.0 is exactly
@property Float Volume Volume size, Range 0-1.0
@property BOOL Enablerate Whether the playback rate is allowed to change
@property Float Rate Playback rate, range 0.5-2.0, if 1.0 is playing normally, if you want to modify the playback rate you must set Enablerate to Yes
@property Nstimeinterval CurrentTime Current playback duration
@property (readonly) Nstimeinterval Devicecurrenttime The output device plays the audio time, note that if the playback is paused this time will also continue to accumulate
@property Nsinteger Numberofloops Loop the number of times, if 0 does not loop, if less than 0 infinite loop, greater than 0 indicates the number of cycles
@property (readonly) nsdictionary *settings Audio playback settings information, read-only
@property (getter=ismeteringenabled) BOOL meteringenabled Whether audio measurement is enabled, default is no, once enabled audio measurement can be updated by the Updatemeters method
Object methods Description
-(Instancetype) Initwithcontentsofurl: (nsurl *) URL error: (Nserror *) outerror Use the file URL to initialize the player, note that this URL cannot be HTTP Url,avaudioplayer does not support loading network media streams, only local files can be played
-(Instancetype) Initwithdata: (NSData *) Data error: (Nserror *) outerror Using NSData to initialize the player, note that the use of this method must be consistent with the file format and file suffix, otherwise error, so it is more recommended than this method or-(Instancetype) Initwithdata: (NSData *) data Filetypehint: (NSString *) utistring Error: (nserror * *) Outerror method initialization
-(BOOL) Preparetoplay; Load the audio file into the buffer, note that this method will also be called implicitly even if the audio file is not loaded into the buffer program before playing.
-(BOOL) play; Play audio files
-(BOOL) Playattime: (nstimeinterval) time Start playing audio at a specified time
-(void) pause; Pause Playback
-(void) stop; Stop playing
-(void) updatemeters Update audio measurements, note that if you want to update audio measurements, you must set meteringenabled to Yes, and you can get instant audio decibel information with audio measurements
-(float) Peakpowerforchannel: (Nsuinteger) channelnumber; Gets the decibel peak of the specified channel, note that if you want to get a decibel spike, you must call the Updatemeters method before
-(float) Averagepowerforchannel: (Nsuinteger) channelnumber Gets the decibel average of the specified channel, and note that if you want to obtain a decibel average, you must call the Updatemeters method
@property (nonatomic, copy) Nsarray *channelassignments Get or set playback channels
Proxy method Description
-(void) audioplayerdidfinishplaying: (Avaudioplayer *) player successfully: (BOOL) flag Audio playback Complete
-(void) Audioplayerdecodeerrordidoccur: (Avaudioplayer *) Player ERROR: (NSERROR *) error Audio decoding error occurred

The following is a simple player using the Avaudioplayer implementation, in this player to play, pause, display playback progress function, of course, such as adjusting the volume, set the cycle mode, even the sound wave image (by analyzing the audio decibel value) and other functions can be achieved, here is no longer one by one demo. The interface effect is as follows:

- (void) viewdidload {[Super viewdidload]; //Do any additional setup after loading the view.    }-(Ibaction) Stop: (ID) Sender {/** * Stops playback and undoes the setup needed for playback. */[_player stop]; //Specify the time that you play_player.currenttime =0;}-(Ibaction) Start: (ID) Sender {//Get MP3 PathNsurl *mp3url = [[NSBundle mainbundle] Urlforresource:@"Bbqne.mp3"Withextension:nil]; Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_player=[[Avaudioplayer alloc] Initwithcontentsofurl:mp3url Error:nil]; /** * A Boolean value, specifies whether playback rate adjustment are enabled for the audio player. */_player.enablerate=YES; /** * Prepares the audio player for playback by preloading it buffers. */[_player Preparetoplay]; //You can't add a global breakpoint here, or it will collapse.        /** * The number of times a sound would return to the beginning, upon reaching the end, to repeat playback. */_player.numberofloops=maxfloat; _player.Delegate=Self ; _displaylink=[Cadisplaylink displaylinkwithtarget:self selector: @sel                Ector (Playmusic)];                [_displaylink Addtorunloop:[nsrunloop Mainrunloop] formode:nsrunloopcommonmodes]; Avaudiosession*session =[Avaudiosession sharedinstance]; [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (                                                   Handleinterruption:) name:avaudiosessioninterruptionnotification Object: Session]; _timeslider.maximumvalue=_player.duration;        }); /** * Plays a sound asynchronously. */[_player play]; }/** * Change the progress bar*/- (void) Playmusic {_timeslider.value=_player.currenttime; intSEC =_timeslider.value; _timelabel.text= [NSString stringWithFormat:@"%02d", sec];        [_player Updatemeters]; DoubleLowpassresults = POW (Ten, (0.05* [Self.player Peakpowerforchannel:0])); floatresult =Ten* (float) Lowpassresults; NSLog (@"%.2f", result);}- (void) Handleinterruption: (Nsnotification *) Noti {//Handling Interrupt EventsNSLog (@"Handling Interrupt Events");}-(Ibaction) Pause: (ID) Sender {/** * pauses playback; sound remains ready to resume playback from where it is left off. */[_player pause];}/** * Specify the current playback time*/-(Ibaction) timechanged: (UISlider *) Sender {_player.currenttime=Sender.value;}/** * Change playback speed*/-(Ibaction) Ratechange: (UISlider *) Sender {_player.rate=Sender.value;}/** * Change the playback volume*/-(Ibaction) volunmchanged: (UISlider *) Sender {_player.volume=Sender.value;}

Recording

The Avfoundation framework also has a Avaudiorecorder class that specializes in recording operations, and it also supports multiple audio formats. Similar to Avaudioplayer, you can completely consider it as a tape recorder control class, the following are commonly used properties and methods:

@property (readonly, getter=isrecording) BOOL recording; Whether recording is being recorded, read-only
@property (readonly) Nsurl *url Audio file address, read-only
@property (readonly) nsdictionary *settings Recording file settings, read-only
@property (readonly) Nstimeinterval currenttime Recording time is long, read only, note is only available in the recording state
@property (readonly) Nstimeinterval Devicecurrenttime Enter the length of the setting, read-only, and note that this property is accessible all the time
@property (getter=ismeteringenabled) BOOL meteringenabled; Whether to enable recording measurement, if you enable recording measurement can obtain data such as decibel recording
@property (nonatomic, copy) Nsarray *channelassignments Channel for current recording
Object methods Description
-(Instancetype) Initwithurl: (nsurl *) URL settings: (nsdictionary *) settings error: (Nserror *) outerror Sound Recorder Object Initialization method, note that the URL must be local file url,settings is the recording format, encoding and other settings
-(BOOL) Preparetorecord Prepare the recording, which is used primarily to create buffers, which are automatically called when the record is called, if not manually 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 as long as you specify
-(BOOL) Recordattime: (nstimeinterval) Time forduration: (nstimeinterval) duration Start recording at a specified time and specify the length of the recording
-(void) pause; Pause Recording
-(void) stop; Stop Recording
-(BOOL) deleterecording; Delete the recording, note that the recorder must be in a stopped state at this time
-(void) updatemeters; Update the measurement data, note that only meteringenabled is yes this method is available
-(float) Peakpowerforchannel: (Nsuinteger) channelnumber; Specify the measurement peaks of the channel, and note that only the updatemeters is called after the value
-(float) Averagepowerforchannel: (Nsuinteger) channelnumber Specify the measured mean of the channel, and note that only the value is updatemeters after the call
Proxy method Description
-(void) audiorecorderdidfinishrecording: (Avaudiorecorder *) Recorder successfully: (BOOL) flag Finish recording
-(void) Audiorecorderencodeerrordidoccur: (Avaudiorecorder *) Recorder error: (NSERROR *) error

The construction of the program is mainly divided into the following steps:

    1. Set the audio session type to Avaudiosessioncategoryplayandrecord because the recording and playback operations are involved in the program.
    2. Create a Sound Recorder avaudiorecorder, specify the path to save the recording and set the recording properties, note that the sample rate and the number of bits required for a typical recording file are not high, and need to be set appropriately to ensure the size and effect of the recording file.
    3. Set up the Sound Recorder agent to play the recording after the recording is complete, and open the recording measurement to ensure real-time access to audio intensity. (Note the sound intensity range-160 to 0, 0 for maximum input)
    4. Create an audio player Avaudioplayer to play the recording after the recording is complete.
    5. Create a timer to refresh the recording measurements in real time and update the recording intensity to uiprogressview display.
    6. 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 the recovery time and so on.

Here's the main code

Audio playback and recording of iOS development

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.