Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regulating the volume of SKAction playSoundFileNamed:

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.

like image 271
Dobroćudni Tapir Avatar asked Dec 04 '13 09:12

Dobroćudni Tapir


2 Answers

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!

like image 195
Chris Brasino Avatar answered Oct 06 '22 00:10

Chris Brasino


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:.

like image 33
Giordano Scalzo Avatar answered Oct 06 '22 00:10

Giordano Scalzo