Search code examples
iossprite-kitskaction

Sprite kit detect sound completion


I have used sequence of action and one of the action plays sound for me.

        SKAction *wait = [SKAction waitForDuration:1];

        NSString* completion_sound = self.gameData[@"level_data"][@"completion_sound"];
        SKAction *playSound = [SKAction playSoundFileNamed:completion_sound waitForCompletion:NO];

        SKAction *completion = [SKAction runBlock:^{

            // do some code here.

        }];

        SKAction *sequence = [SKAction sequence:@[wait, playSound, completion]];

        [self runAction:sequence];

But I want to detect a completion of sound. seems like sound is still playing while block is invoking.


Solution

  • It appears you are passing NO for the waitForCompletion: argument and it should be YES.

    If YES, the duration of this action is the same as the length of the audio playback. If NO, the action is considered to have completed immediately.

    So change to YES in this line of code...

    SKAction *playSound = [SKAction playSoundFileNamed:completion_sound waitForCompletion:YES];
    

    ...and the playSound action duration will be the length of the sound, therefor the 'completion block' SKAction *completion will not be executed until the sound is finished.