While looking at codes required to play an audio file, I found huge differences between different books/resources.
In the book iOS 4 Programming Cookbook, it talks about:
1. Adding " <AVAudioPlayerDelegate> " to the .h file of the ViewController
2. Create 2 methods:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
- (void) startPlayingAudio;
if (self.audioPlayer != nil) {
if([self.audioPlayer isPlaying] == YES){
[self.audioPlayer stop];
}
self.audioPlayer = nil;
}
Wow, that is quite a lot of work/code just to play an Audio file.
So far, the best I got are the following 2, which is quite similar:
1st one is from iOS Recipes: Tips and Tricks for Awesome iPhone and iPad Apps. The code is as below:
NSURL *url = [NSURL fileURLWithPath:
[NSString stringWithFormat:@"%@/correct01.caf",
[[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
2nd one is from the the Core Animation Demo by Bob McCune I mentioned before:
NSString *soundFilePath = [[NSBundle mainBundle]
pathForResource:@"correct01" ofType:@"caf"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *audioPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:nil];
[fileURL release];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
Both are quite similar and much much shorter than the top example above plus many other examples I found on the net.
Let me know if you got better way!
0 comments:
Post a Comment