0

On playing more than 1 songs using AVAudio Player

when the first song get finished - (void)audioPlayerDidFinishPlaying:successfully: get called .

if i use that code it works

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSString *tempString = @"/";
    tempString  = [tempString stringByAppendingString:name];
    NSString *path = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] resourcePath]];
    path = [path stringByAppendingString:tempString];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSError *error;

    AVAudioPlayer  *audioPlayer101 = [[AVAudioPlayer alloc] initWithContentsOfURL:url    error:&error];

    [AppDelegate getAppdelegate].audioPlayerForPlay = audioPlayer101;
    [[AppDelegate getAppdelegate].audioPlayerForPlay play];
} 

It works

however if i does not put the instance in perdefined property of audio player it doesnot play.

here is that code

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSString *tempString = @"/";
    tempString  = [tempString stringByAppendingString:name];
    NSString *path = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] resourcePath]];
    path = [path stringByAppendingString:tempString];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSError *error;

    AVAudioPlayer  *audioPlayer101 = [[AVAudioPlayer alloc] initWithContentsOfURL:url    error:&error];
    [audioPlayer101  play];
} 
lootsch
  • 1,867
  • 13
  • 21
Ankur
  • 98
  • 2
  • 13
  • http://stackoverflow.com/questions/7692866/avaudioplayer-stops-playing-immediately-with-arc – Oleg Trakhman Mar 16 '14 at 14:51
  • Long story (see link in comment above) short, ARC releases you `audioPlayer101` right after you create it; the easiest way to fix is to make storng ivar, like in your first chunk of code (where you have ivar in AppDelegate) – Oleg Trakhman Mar 16 '14 at 14:56
  • In my scenario i have multiple audio players playing at the same time and i need the instance of each audio player separately. is there any solution to implement the second test case perfectly. – Ankur Mar 16 '14 at 15:03

1 Answers1

0

the ARC code

AVAudioPlayer  *audioPlayer101 = [[AVAudioPlayer alloc] initWithContentsOfURL:url    error:&error];
[audioPlayer101  play];

will be compile to for Non-ARC

AVAudioPlayer  *audioPlayer101 = [[AVAudioPlayer alloc] initWithContentsOfURL:url    error:&error];
[audioPlayer101  play];
[audioPlayer101 release];

And the audioPlayer101 will be released as soon as it create, because system will not retain it automatically and release lead to dealloc make play stop.

If you use instance.audioPlayerForPlay = audioPlayer101; like your code, and the property of audioPlayerForPlay is strong, the play will be retained by instance, so can the play can keep playing. You can try set audioPlayerForPlay to beweak`, the previous code will not play as well.

simalone
  • 2,768
  • 1
  • 15
  • 20