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 slider in my game. I can easily control background music since i play it via AVAudioPlayer, but all sound effects are played via SKAction.
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!
Unfortunately you can't modify the volume using SKAction, so you have to use AVAudioPlayer for your effects too. You could implement a custom playSoundFileNamed:waitForCompletion:volume: using runBlock as you already thought, so your code won't be very different then using playSoundFileNamed:waitForCompletion:.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With