IOS audio playback uses the avfoundation framework. It contains three main classes: avaudioplayer, avaudiorecorder, and avaudiosession. They are responsible for audio playback, recording, and configuration, and all have the corresponding delegate protocol. Supported formats include: CAF, m4a, MP3, AIF, WAV, AU, SND, and AAC. provides basic playback operations: Create, prepare, play, pause, skip, and stop, and supports the use of multiple avaudioplayer objects. Supports volume control, loop playback, and left-right channel settings.
The avaudioplayerdelegate Protocol has the following important methods:
The audioplayerbegininterruption method is called when an application is interrupted (for example, an application is called by answering a call or pressing the Home key. Audioplayerendinterruption method, which is called when the interrupt ends and is returned to the application. Audioplayerdidfinishplaying: successfully: method. This method is called after the audio playback is complete. If the value of successfully is yes, the audio is played normally. If the value of NO, the playback ends because the audio data decoding fails. Audioplayerdecodeerrordidoccur: Error: method. This method is called when an audio decoding error occurs during playback.
Instance: 1. Create an empty application project and add the homeviewcontroller page.
The homeviewcontroller. H code is as follows:
# Import <uikit/uikit. h> # import <avfoundation/avfoundation. h> @ interface homeviewcontroller: uiviewcontroller <avaudioplayerdelegate> {}
@ End
The homeviewcontroller. m code is as follows:
# Import "homeviewcontroller. H "@ interface homeviewcontroller () @ end @ implementation homeviewcontroller-(void) playaudiofile :( nsstring *) soundfilename {nsstring * filename = [[nsbundle mainbundle] pathforresource: soundfilename oftype: @ "MP3"]; nsurl * fileurl = [nsurl fileurlwithpath: Filename]; nserror * error = nil; avaudioplayer * player = [[avaudioplayer alloc] initwithcontentsofurl: fileurl error: & E Rror]; If (! Player) {} else {[Player setnumberofloops:-1]; // The default value is 0, indicating that the playback ends once. If it is set to a negative value, the audio content will be played continuously. [PLAYER setdelegate: Self]; [player play] ;}}
// Pause playing when the program is interrupted
-(Void) audioplayerbegininterruption :( avaudioplayer *) player {[Player pause];}
// Resume playing when the program ends and returns to the program.
-(Void) audioplayerendinterruption :( avaudioplayer *) player {[player play];}-(void) viewdidload {[self playaudiofile: @ "mm"]; // play the audio [Super viewdidload];}
@ End
Download source code:/files/Hanjun/audio.rar