Regulating the volume of SKAction playSoundFileNamed:

前端 未结 3 1166
心在旅途
心在旅途 2021-02-13 12:05

Is there a way to regulate the volume of sound played via SKAction playSoundFileNamed:waitForCompletion:.

I would like to implement a simple music & sound effects sl

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-13 12:38

    Here is my code for how i handled this problem

    NSError *error;
    NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"pew-pew-lei" withExtension:@"caf"];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
    [player setVolume:masterVolume];
    [player prepareToPlay];
    
    SKAction*   playAction = [SKAction runBlock:^{
        [player play];
    }];
    SKAction *waitAction = [SKAction waitForDuration:player.duration+1];
    SKAction *sequence = [SKAction sequence:@[playAction, waitAction]];
    
    [self runAction:sequence];
    

    The masterVolume variable is just some preset variable i have that the user can change from 0.0-1.0

    The waitAction ensures that the player doesn't get removed before it has played the entire sound

    Hope this helps!

提交回复
热议问题