audioplayerdidfinishplaying问题! iphone sdk

时间:2011-05-08 20:21:25

标签: iphone objective-c core-audio avfoundation

声音结束后,可以播放另一种声音......但是在这段代码中声音混合......我该如何解决?

-(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] initWithContentsOfURL:[NSURL fileURLWithPath: songPath] error:NULL];
                [audioPlayer setDelegate:self];
                [audioPlayer play];
   }
}


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

2 个答案:

答案 0 :(得分:1)

一旦用户点击音频播放器播放的按钮,但似乎音频未完成并且用户再次点击它,音频播放器的另一个对象是用另一个音频文件的引用创建的。这使得两个甚至更多的音频同时播放。嗯,解决方案很简单。只需检查每次按下按钮的时间,如果播放器已经播放,如果是,请停止播放器并释放并使用新的文件URL引用创建新实例。为此,您应该合成audioPlayer并将其用作,< / p>

-(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; 
  }

答案 1 :(得分:0)

您的代码不是真的可以理解,但我认为我的目标是什么。

要实现它,假设您有一个NSArray *itemsToPlay。 在最开始时(即当用户点击你的按钮时)它会充满你所有的声音。

用户点击按钮后,会调用IBAction。在那里,您从itemsToPlay中选择第一个声音(并将其从此容器中删除)并告诉audioPlayer播放。

玩家完成游戏后,会调用audioPlayerDidFinishPlaying:successfully:。在那里,您再次从itemsToPlay中选择第一项,并使用它重新启动audioPlayer。再说一遍,说audioPlayer

itemsToPlay为空时,此循环将结束。