SceneKit Audio - How to add SCNPlayer to SCNNode and just play sound

I am currently using this code (inside a SCNNode subclass) to play sound in SceneKit.

let audioSource = SCNAudioSource(named: "coin.wav") let audioPlayer = SCNAudioPlayer(source: audioSource) self.addAudioPlayer(audioPlayer) 

This is not ideal as it populates an array of audioPlayers every time I play a new sound. Ideally, I can have one SCNAudioPlayer for each sound I want to play, and just call the play function to play it.

Unfortunately, I could not find the playback function. It also annoys me that SCNAudioPlayer automatically plays sound when added to a node. But I want to tune my scene without any sounds, and then at a later point, play the sounds.

What is the correct way to use SceneKit Audio Engine?

+4
source share
2 answers

To play a single sound like / if, when pressed or otherwise, an event and / or input is triggered ...

There is a special "action": SCNAction.playAudioSource

 class func playAudioSource(_ source: SCNAudioSource, waitForCompletion wait: Bool) -> SCNAction 

Then, to play the sound, run it on node:

 myNode.runAction(myActionName) 
+4
source

You can use an action as previously answered, as it is syntactically easier to use.

SCNAudioPlayers are recycled by the engine, so you don’t need to worry about their lifespan unless you need to change them during the game. The idea behind the SceneKit sound engine is that sounds should behave just like SCNNodes. If there is a node on the scene graph, then it is visible, as well as its geometry, particle systems, etc. Therefore, if a sound is attached to a node, it should start playback immediately if the node is visible (see and stop if it is hidden).

The audio source represents only the actual audio data. Think of it as a texture: it loads once and can refer to a number of materials on a number of three-dimensional nodes. The audio player creates a sound source so that you can play it on multiple nodes at the same time, just like you would use the same material for different geometries on different nodes.

We hope that this helps and gives some perspective on the choice of design,

S.

+4
source

All Articles