Denis
Denis

Reputation: 417

AVAudioPlayer only calls audioPlayerDidFinishPlaying twice

I'm trying to create a sort of audio playlist using AVAudioPlayer. So I've used the following code:

.h

<AVAudioPlayerDelegate>
{
    AVAudioPlayer *audioPlayer;
}

@property (nonatomic, retain) AVAudioPlayer *audioPlayer;

.m

@synthesize audioPlayer;

 - (void)viewDidLoad 
{
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    audioPlayer.numberOfLoops = 0;
    audioPlayer.delegate = self;
    [audioPlayer play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (flag)
    {
        [player release];

        currentSong = currentSong + 1;
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[songs objectAtIndex:currentSong] ofType:@"mp3"]];

        artist.text = [artists objectAtIndex:currentSong];
        song.text = [songs objectAtIndex:currentSong];

        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

        audioPlayer.delegate = self;
        audioPlayer.numberOfLoops = 0;

        [audioPlayer initWithContentsOfURL:url error:nil];
        [audioPlayer play];
    }
}

This works for two songs, but after this there isn't any audio. Any idea why this is?

Thanks, Denis

Upvotes: 0

Views: 1518

Answers (2)

Chandan Shetty SP
Chandan Shetty SP

Reputation: 5117

1.Just maintain an array.
2.Once you create an instance of audioPlayer - add to the array and call play and release the instance of audioPlayer(since it will get retained once you added to array).
3.In audioPlayerDidFinishPlaying remove the audioPlayer from that array.

So you can play multiple files at a time

Upvotes: 0

coneybeare
coneybeare

Reputation: 33101

In this line you are initing an audio player:

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

Then you are initing it again in this line (unneeded duplication, and probably an additional retain):

 [audioPlayer initWithContentsOfURL:url error:nil];

Then the next time the loop comes around, even though you release it using the line

[player release];

…there is a problem as it is still in memory, tying up a hardware codec or wasting resources. Try removing the second initWithContents… line as it is unnecessary.

Upvotes: 1

Related Questions