Support 3D Spatial Audio Effects

Apple Game Frameworks and Technologies — by Tammy Coron (147 / 193)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Create Additional Game Scenes | TOC | Next Steps 👉

Wouldn’t it be neat to have the background music get louder as the player approaches the exit? (Yeah, I thought so, too.) One of the neat things you can do with SpriteKit and the SKAudioNode class is support 3D spatial audio effects, such as using positional sound based on where a listener node is located.

The listener node is an instance property on an SKScene object. Typically, you’d set the camera or player node to be the scene’s listener. In Val’s Revenge, you’ll set the player node as the listener.

Switch to the GameScene.swift file. Below the setupPlayer() method, add the following code:

​ ​func​ ​setupMusic​() {
​ ​let​ musicNode = ​SKAudioNode​(fileNamed: ​"music"​)
​ musicNode.isPositional = ​false​

​ ​// Make the audio node positional​
​ ​// so that the music gets louder as​
​ ​// the player gets closer to the exit​
​ ​if​ ​let​ exit = ​childNode​(withName: ​"exit"​) {
​ musicNode.position = exit.position
​ musicNode.isPositional = ​true​
​ listener = player
​ }

​ ​addChild​(musicNode)
​ }

This code first makes sure there’s an exit node available within the scene. If so, it sets the position of the SKAudioNode object to match the exit node. It also sets the player node to the scene’s listener.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.