Massive fps drops when AVAudioPlayer ist triggered repeatedly (Sprite Kit)

蹲街弑〆低调 提交于 2019-12-11 10:48:09

问题


I am creating an iOS-Game in Sprite Kit in which you can fire a water gun. As long as the water gun is fired, a slash-sound is played. Since I implemented this feature, I have massive fps-problems when the sound effect ist triggered repeatedly with the touches-began-method.

Is there any possibility to fix that issue?

@property (nonatomic) AVAudioPlayer *splashSound;

-(id)initWithSize:(CGSize)size {

    NSError *error3;
    NSURL *splashURL = [[NSBundle mainBundle] URLForResource:@"splash" withExtension:@"caf"];
    self.splashSound = [[AVAudioPlayer alloc]initWithContentsOfURL:splashURL error:&error3];
    self.splashSound.numberOfLoops = 1;
    [self.splashSound prepareToPlay];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */
    startGamePlay = YES;
    if (self.waterCapacity != 0){
    waterSprayed = YES;
    [self.splashSound play]; // sound starts when screen is touched
    [self.currentWasser sprayWater];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.currentWasser removeActionForKey:@"water"];
    [self.splashSound pause]; // sound is paused when touches ended
    waterSprayed = NO;
}

回答1:


Fixed it with an UILongPressGestureRecognizer: works perfectly. So happy!

- (void)didMoveToView:(SKView *)view
{
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(delayedSplashSound:)];
    longGesture.minimumPressDuration = 0.15;
    [view addGestureRecognizer:longGesture];
}

- (void)delayedSplashSound:(UITapGestureRecognizer *)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        [self.splashSound play];
    }else if (recognizer.state == UIGestureRecognizerStateEnded){
        [self.splashSound pause];
        [self.currentWater removeActionForKey:@"water"];
        waterSprayed = NO;
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    startGamePlay = YES;
    if (self.waterCapacity != 0){
    waterSprayed = YES;
    [self.currentWater sprayWater];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.currentWater removeActionForKey:@"water"];
    waterSprayed = NO;
}



回答2:


I have another work-around for the frame-drops when using AVAudioPlayer.play() and AVAudioPlayer.stop() with an infinite loop. Instead of calling play() and stop(), just call play() once and set yourPlayerInstance.volume=0.0 and yourPlayerInstance.volume=1.0. This solved the frame-glitches/-drops for me - perfect 60 fps instead of drops to ~40 fps.



来源:https://stackoverflow.com/questions/25646583/massive-fps-drops-when-avaudioplayer-ist-triggered-repeatedly-sprite-kit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!