December 2012
Intermediate to advanced
834 pages
27h
English
You want to be able to play an audio file in your application.
Use the AV Foundation (Audio and Video 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 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)viewDidLoad{[superviewDidLoad];self.view.backgroundColor=[UIColorwhiteColor];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!=nil){/* Set the delegate and start playing */self.audioPlayer.delegate=self;if([self.audioPlayerprepareToPlay]&&[self.audioPlayerplay]){/* Successfully started playing */}else{/* Failed to play */}}else{/* Failed to instantiate AVAudioPlayer */}});}
As you ...
Read now
Unlock full access