Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioPlayer Number Of Loops only taking effect after being played through once

I'm a little stumped by this weird occurrence:

I have a UIButton, which once tapped either sets a loop for an audio player, or resets it to 0 (no loop). Here is the method -

-(void)changeLoopValueForPlay:(int)tag toValue:(bool)value{
    AVAudioPlayer *av =  [self.playerArray objectAtIndex:tag];
    if(value){
        [av setNumberOfLoops:100];
        [av prepareToPlay];
    }
    else{
        [av setNumberOfLoops:0];
    }
}

Now for some reason, the loop will only take effect after the player plays through the audio one time, meaning that the looping value doesn't take affect immediately, but the "numberOfLoops" value of the player is in fact set to 100 when I check its value before playing. I'm assuming this has something to do with the initialization or loading of the player, but I don't re-initialize it between those two plays (one without loop, the other with). Any idea why this is happening? If you want to see any other code please let me know.

like image 445
royherma Avatar asked Nov 26 '13 04:11

royherma


2 Answers

This fixed the problem, however I feel as if this is a work-around instead of a direct solution. What I did is just create a new AVAudioPlayer with the numberOfLoops value set to whatever it is I wanted and replace that player with the existing player, instead of changing the value of the already existing player.

like image 111
royherma Avatar answered Sep 23 '22 16:09

royherma


I workaround the issue by abandoning numberOfLoops altogether and doing my own logic instead.

First, set the delegate of the AVAudioPlayer:

self.audioPlayer.delegate = self;

Next, implement -audioPlayerDidFinishPlaying:successfully: of the delegate:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag
{
    if(flag && <#(bool)i_want_to_repeat_playing#>)
    {
        [self.audioPlayer play];
    }
}

Just replace <#(bool)i_want_to_repeat_playing#> with your desired logic, e.g., check if a counter has reached a certain threshold.

like image 30
Pang Avatar answered Sep 23 '22 16:09

Pang