开发者

audioplayerdidfinishplaying problem! iphone sdk

开发者 https://www.devze.com 2023-03-03 23:43 出处:网络
After a sound has finished, another sound could play...but in this code sounds are mixing...How can I fix it?

After a sound has finished, another sound could play...but in this code sounds are mixing...How can I fix it?

-(IBAction) ... {
   for ( ...) {
     if (compare(Output, N1)) {
       songPath = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"wav"];
     }
     if (compare(Output, N2)) {
       songPath = [[NSBundle mainBundle] pathForResource:@"b" ofType:@"wav"];
     }
     audioPlayer=[[AVAudioPlayer alloc]开发者_StackOverflow社区 initWithContentsOfURL:[NSURL fileURLWithPath: songPath] error:NULL];
                [audioPlayer setDelegate:self];
                [audioPlayer play];
   }
}


-(void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player successfully: (BOOL) flag {
  NSLog(@"Song FINISHED!!!!!!");
  [player release];
}


Once the user taps the button the audio player plays but it seems like if the audio is not finished and user taps it again the another object of audio player is created with the another reference to the audio file. This makes two or evenmore audio to play at the same time. Well, the solution is simple. Just check to see every time when the button is tapped, if the player is already playing, if so stop the player and release and create a new instance with new file url reference .To do this you should synthesize audioPlayer and use it as,

-(IBAction) ... {
   for ( ...) {
   if (compare(Output, N1)) {
     songPath = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"wav"];
   }
   if (compare(Output, N2)) {
     songPath = [[NSBundle mainBundle] pathForResource:@"b" ofType:@"wav"];
   }
   if(self.audioPlayer){
     self.audioPlayer.delegate=nil;
     self.audioPlayer=nil;
    }
   self.audioPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:
                           [NSURL fileURLWithPath: songPath] error:NULL];
   [self.audioPlayer setDelegate:self];
   [self.audioPlayer play];
  }
 }


-(void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player successfully: (BOOL) flag {
     NSLog(@"Song FINISHED!!!!!!");
     [self.audioPlayer setDelegate:nil];   
     self.audioPlayer=nil; 
  }


Your code isn't really understandable, but I think I get what your goal is.

To implement it, lets say, you have an NSArray *itemsToPlay. In the very beginning (i.e. when user taps your button) it's filled with all your sounds.

After user taps the button, IBAction is called. There you pick the first sound from itemsToPlay (and remove it from this container) and tell the audioPlayer to play.

After player is finished playing, audioPlayerDidFinishPlaying:successfully: is called. There you once again pick the first item from itemsToPlay and re-init your audioPlayer with it. Again, say audioPlayer to play.

This cycle will end when itemsToPlay is empty.

0

精彩评论

暂无评论...
验证码 换一张
取 消