October 2013
Intermediate to advanced
1053 pages
28h 7m
English
You want to be able to play an audio file in your application.
Use the AV Foundation framework’s AVAudioPlayer class.
The AVAudioPlayer class in the
AV Foundation framework can play back all audio formats supported by
iOS. The delegate property of an
instance of AVAudioPlayer allows you
to get notified by events, such as when the audio playback is
interrupted or when an error occurs as a result of
playing an audio file. Let’s have a look at a simple example that
demonstrates how we can play an audio file from the application’s
bundle:
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)playersuccessfully:(BOOL)flag{NSLog(@"Finished playing the song");/* The [flag] parameter tells us if the playback was successfullyfinished or not */if([playerisEqual:self.audioPlayer]){self.audioPlayer=nil;}else{/* Which audio player is this? We certainly didn't allocatethis instance! */}}-(void)viewDidLoad{[superviewDidLoad];dispatch_queue_tdispatchQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);dispatch_async(dispatchQueue,^(void){NSBundle*mainBundle=[NSBundlemainBundle];NSString*filePath=[mainBundlepathForResource:@"MySong"ofType:@"mp3"];NSData*fileData=[NSDatadataWithContentsOfFile:filePath];NSError*error=nil;/* Start the audio player */self.audioPlayer=[[AVAudioPlayeralloc]initWithData:fileDataerror:&error];/* Did we get an instance of AVAudioPlayer? */if(self.audioPlayer ...
Read now
Unlock full access