1

How to play audio under scenekit?

let source = SCNAudioSource(fileNamed: "sample.mp3")
let action = SCNAction.playAudio(source!, waitForCompletion: true)
        
let scene = SCNScene()
self.scenekitView.scene = scene
scene.rootNode.runAction(action)  // no sound

2 Answers 2

1

Try changing 'let scene' to a var scene, then handle the rest in viewDidLoad as follows:

class GameViewController: UIViewController {

    var SoundAction = SCNAction()
    var SoundNode = SCNNode()
    var scene = SCNScene()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Change this
        scene = SCNScene(named: "art.scnassets/ship.scn")!

        let cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()
        scene.rootNode.addChildNode(cameraNode)
        cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)

        let ship = scene.rootNode.childNode(withName: "ship", recursively: true)!
        ship.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 1)))

        let audioSource = SCNAudioSource(named: "MenuWinner.caf")!
        audioSource.volume = 1.0
        SoundAction = SCNAction.playAudio(audioSource, waitForCompletion: false)

        let scnView = self.view as! SCNView
        scnView.scene = scene
        scnView.allowsCameraControl = true
        scnView.showsStatistics = true
        scnView.backgroundColor = UIColor.black

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        scnView.addGestureRecognizer(tapGesture)
    }

    @objc
    func handleTap(_ gestureRecognize: UIGestureRecognizer) {
        scene.rootNode.addChildNode(SoundNode)
        SoundNode.runAction(SoundAction)
    }
0

source.load() fixes this issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.