Bhavin_m
Bhavin_m

Reputation: 2784

How to play more than two songs using AVAudioPlayer

I want to play more than two song in my app. how do I can do it using AVAudioPlayer ?

Upvotes: 0

Views: 1109

Answers (1)

Nathan S.
Nathan S.

Reputation: 5388

I was going to type up the answer, but google provides a perfectly good answer:

http://www.iphonedevsdk.com/forum/iphone-sdk-development/27285-play-sequence-audio-files-avaudioplayer.html

The first piece of code from the page will just call all the sounds in sequence:

- (void)playSoundSequence { 

    // Make array containing audio file names 
    NSArray  *theSoundArray = [NSArray arrayWithObjects:@"one",@"two",nil];

    int totalSoundsInQueue = [theSoundArray count];

    for (int i=0; i < totalSoundsInQueue; i) {

        NSString *sound = [theSoundArray objectAtIndex:i];

                // Wait until the audio player is not playing anything
        while(![audioPlayer isPlaying]){

            AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                                pathForResource:sound ofType:@"wav"]] error:NULL];
            self.audioPlayer = player;
            [player release];
            [audioPlayer setVolume:1.0f];
            [audioPlayer play];
            //Increment for loop counter & move onto next iteration
                        i++;      
        }
    }

}

But, you are probably better off using an AVAudioPlayerDelegate:

If you don't want to wait in the loop, you can also make your controller an AVAudioPlayerDelegate and implement

Code:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

This will be called when the end of the audio file is reached, at which point you would start playing the next audio file. audioPlayerDidFinishPlaying will then be called again when that one finishes playing, and you start the next one after that, etc.

Upvotes: 1

Related Questions