Monday, 26 September 2011

How many lines of code required to play an Audio file?

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;

3. in viewDidUnload, you have to do the following:

    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!

No comments:

Post a Comment