Reputation: 4539
I have a method for playing an ambient sound in a sprite kit based game, but I'm wondering if there is a better method. I've seen the ambient sound function in the type ahead, but it seems to be something used by the framework and not something for users of the framework.
Here is what I am currently doing
- (void) playAmbientSound {
[self runAction:self.pAmbientSound completion:^{
[self playAmbientSound];
}];
}
- (void) initSounds {
// Avatar swim sound
self.pSwimSound = [SKAction playSoundFileNamed:@"swim-sound.m4a" waitForCompletion:NO];
// Animation sound
self.pAmbientSound = [SKAction playSoundFileNamed:@"ambient-final.mp3" waitForCompletion:YES];
// Do the Sound in a loop
[self playAmbientSound];
}
Upvotes: 0
Views: 269
Reputation: 16837
SKAudioNode
is the best way to get ambient audio in your game. It is built on top of AVFoundation
, and can be used with SKAction
s to change the volume of the sound or offer a 3d positional sound. Also SKScene
has an audioEngine
property which is of type AVAudioEngine
. This will allow you to manage all of your audio nodes at once for situatuions where you need to stop all audio or change the overall volume of everything.
Upvotes: 2
Reputation: 2222
You can use AVAudioPlayer.
the sample in Objective-C:
Add the audioPlayer
in your .h
file
@property (strong, nonatomic)AVAudioPlayer *audioPlayer;
then in your .m
file use it like this:
NSString *path = [NSString stringWithFormat:@"%@/background.mp3",[[NSBundle mainBundle] resourcePath]];
NSURL *fileURL = [NSURL fileURLWithPath:path];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
_audioPlayer.numberOfLoops = -1; //Infinite
[_audioPlayer prepareToPlay];
[_audioPlayer play];
And in Swift 3 is like this:
func playMusic() {
let path = Bundle.main.path(forResource: "background", ofType: "mp3")
let fileURL = URL(fileURLWithPath: path!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: fileURL)
} catch {
print("error play music")
}
audioPlayer.numberOfLoops = -1 //Infinite
audioPlayer.prepareToPlay()
audioPlayer.play()
}
for infinite loop playing you need to set numberOfLoops equal to -1
Upvotes: 3