Sample CodeiOS, iPadOSReviewed 2026-11-01View on Apple Developer

Creating an immersive ar experience with audio

At a glance

Item Summary
Purpose Use sound effects and environmental sound layers to create an engaging AR experience.
App architecture One storyboard-driven UIKit app target with a single ViewController that is also the ARSCNViewDelegate. It shows a translucent PreviewNode at the screen center until ARKit detects a horizontal plane, then moves the model onto the plane’s node and attaches a looping positional SCNAudioPlayer.
Main patterns One view controller that owns all session, scene, and audio state; ARKit/SceneKit delegate callbacks drive every state change.
Project style Six Swift files in a flat AudioInARKit/ folder: entry points, the controller, the preview node, an ARSCNView raycast extension, and math helpers.
Execution model No Swift concurrency and no app-created queues. State changes happen inside SceneKit renderer callbacks and ARKit session callbacks; one DispatchQueue.main.asyncAfter re-enables the restart button.
State/event model Direct mutation of controller properties (previewNode, objectNode, isRelocalizing, isRestartAvailable) from delegate callbacks. A didSet on isRestartAvailable updates the button.
Key frameworks/packages ARKit, SceneKit (including SCNAudioSource/SCNAudioPlayer), UIKit. The project declares no Swift package.

Project structure

Audio in ARKit.xcodeproj/            one app target, iOS 15.0, iPhone and iPad
AudioInARKit/
├── AppDelegate.swift                ARKit support check, scene configuration
├── SceneDelegate.swift              empty UIWindowSceneDelegate (storyboard scene)
├── ViewController.swift             session, preview, placement, relocalization, audio
├── PreviewNode.swift                SCNNode subclass that smooths the preview position
├── ARSCNView+Raycasts.swift         smartRaycast: existing plane, infinite plane, estimated plane
├── Utilities.swift                  SIMD average, keepLast, float4x4.translation
└── Resources/                       Main storyboard, Info.plist, fireplace.mp3, Assets.scnassets

Structure observations

  • ViewController.swift holds nearly all behavior; the other Swift files are a node subclass and extensions. ViewController adopts only ARSCNViewDelegate (AudioInARKit/ViewController.swift:12), which also delivers the ARSessionObserver callbacks it implements.
  • The Main storyboard creates ViewController and its ARSCNView and connects the view’s delegate outlet to the controller; the code never assigns sceneView.delegate. The Info.plist scene configuration loads that storyboard for SceneDelegate (AudioInARKit/Resources/Info.plist:65).
  • The target builds for iPhone and iPad with an iOS 15.0 deployment target (Audio in ARKit.xcodeproj/project.pbxproj:346, Audio in ARKit.xcodeproj/project.pbxproj:352).

Overall architecture

Reference code

AudioInARKit/ViewController.swift:208 — plane detection moves the model from the preview onto the plane and starts audio

    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
        // Continue if the anchor is a plane, and the object has not been placed
        guard anchor is ARPlaneAnchor, previewNode != nil else { return }
        
        // Separate the object node from the preview node
        objectNode.removeFromParentNode()
        // Remove `previewNode` from the node hierarchy
        previewNode?.removeFromParentNode()
        previewNode = nil
        
        // Create a player from the source and add it to `objectNode`
        objectNode.addAudioPlayer(SCNAudioPlayer(source: audioSource))
        // Place object node on top of the plane's node
        node.addChildNode(objectNode)
        // ...
        // Play a positional environment sound layer from the newly placed object
        playSound()
    }

Interpretation

Observed: the app has two phases, and objectNode.parent is the phase flag. While objectNode has no parent, each frame callback sets up a preview (if needed) and repositions it (AudioInARKit/ViewController.swift:196). The first plane anchor ends the preview phase. Because SceneKit positional audio follows the node it is attached to, placing objectNode under the plane’s node is what positions the sound in the room.

Inference: the sample does not separate model, view, and controller layers because all state is SceneKit node state plus a few flags; a single controller keeps the two phases visible in one file.

Ownership and state

Ownership evidence

AudioInARKit/ViewController.swift:22 — controller-owned scene and audio state

class ViewController: UIViewController, ARSCNViewDelegate {
    // ...
    /// Source for audio playback
    var audioSource: SCNAudioSource!
    
    /// Holds a preview of the object while plane detection is in progress
    var previewNode: PreviewNode?
    
    /// Contains the virtual object that is placed in the real world
    var objectNode: SCNNode!
    
    /// Relocalization vars
    var isRelocalizing = false
    
    /// The center of the screen, used for determining the location of the preview and (placed) object nodes.
    var screenCenter: CGPoint!
    
    /// Marks if the AR experience is available for restart.
    var isRestartAvailable = true {
        didSet { restartExperienceButton.isEnabled = isRestartAvailable }
    }
    // ...
}
Owner Object or state Relationship Mutation authority
ViewController audioSource Created, set to loop, and preloaded once in setUpAudio() (AudioInARKit/ViewController.swift:290) ViewController
ViewController objectNode Created in viewDidLoad, then replaced in resetTracking() and setUpPreviewNode() (AudioInARKit/ViewController.swift:54, AudioInARKit/ViewController.swift:111, AudioInARKit/ViewController.swift:152) ViewController
ViewController previewNode Created in setUpPreviewNode() and cleared on placement or reset (AudioInARKit/ViewController.swift:159, AudioInARKit/ViewController.swift:216) ViewController
PreviewNode The wrapped objectNode Adds it as a child at 50% opacity (AudioInARKit/PreviewNode.swift:26) PreviewNode; the controller detaches it on placement
PreviewNode recentPreviewNodePositions private ring of the last eight positions (AudioInARKit/PreviewNode.swift:18) Only PreviewNode
objectNode SCNAudioPlayer Added in renderer(_:didAdd:for:) and replaced in playSound() (AudioInARKit/ViewController.swift:219, AudioInARKit/ViewController.swift:299) ViewController; cleared in viewWillDisappear
ViewController isRelocalizing, isRestartAvailable, screenCenter Plain stored properties ViewController

Observed: playSound() first removes every audio player and then adds a new one, so after placement objectNode ends up with exactly one player even though renderer(_:didAdd:for:) also adds one just before calling it (AudioInARKit/ViewController.swift:301). The orientation constraint closure captures self strongly (AudioInARKit/ViewController.swift:163); Inference: harmless here because objectNode is replaced on reset and the controller lives for the app.

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Per-frame callback renderer(_:updateAtTime:) Sets up and repositions the preview node directly, with no queue hop. The callback’s thread is not established in source. AudioInARKit/ViewController.swift:196
Anchor callback renderer(_:didAdd:for:) Reparents objectNode, adds audio, and re-runs the session configuration directly AudioInARKit/ViewController.swift:208, AudioInARKit/ViewController.swift:226
Session callbacks session(_:cameraDidChangeTrackingState:), session(_:didFailWithError:), interruption callbacks Write sessionInfoLabel.text and call resetTracking() or relocalization helpers directly; the source sets no delegateQueue AudioInARKit/ViewController.swift:232, AudioInARKit/ViewController.swift:256
Main-queue delay DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) Re-enables restart, which updates the button through didSet AudioInARKit/ViewController.swift:188
Shared-state safety None objectNode and previewNode are written from renderer callbacks and from resetTracking() (called by the button and session callbacks) without a lock or queue AudioInARKit/ViewController.swift:105

Reference code

AudioInARKit/ViewController.swift:183 — the only explicit scheduling in the sample

    @IBAction private func restartExperience(_ sender: UIButton) {
        guard isRestartAvailable else { return }
        isRestartAvailable = false
        resetTracking()
        // Disable restart for a while in order to give the session time to restart.
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {
            self.isRestartAvailable = true
        }
    }

Not established by source: which threads deliver the SceneKit renderer and ARKit session callbacks, or how objectNode and previewNode stay consistent across them. Inference: the sample relies on the isRestartAvailable cooldown and the objectNode.parent == nil check rather than on synchronization.

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
Delegate callbacks ARSCNViewDelegate (connected in the storyboard) Renderer and session events are the only inputs besides the restart button AudioInARKit/ViewController.swift:12
Tracking state cameraDidChangeTrackingState switch .limited(.relocalizing) hides the object and mutes audio; .normal restores it AudioInARKit/ViewController.swift:247, AudioInARKit/ViewController.swift:240
Audio volume player.audioNode as? AVAudioMixing Volume set to 0.0 during relocalization and back to 1.0 afterward AudioInARKit/ViewController.swift:125, AudioInARKit/ViewController.swift:143
Property observer isRestartAvailable didSet Keeps the restart button’s enabled state in sync AudioInARKit/ViewController.swift:37
Framework import UIKit, SceneKit, ARKit Imported by the controller AudioInARKit/ViewController.swift:8
Package declaration None The project file declares no Swift package Audio in ARKit.xcodeproj/project.pbxproj:346

Class and protocol design

Reference code

AudioInARKit/PreviewNode.swift:38 — smoothing the preview with a private position buffer

class PreviewNode: SCNNode {
    // ...
    func update(for position: SIMD3<Float>, planeAnchor: ARPlaneAnchor?, camera: ARCamera?) {
        lastPosition = position
        if planeAnchor != nil {
            lastPositionOnPlane = position
        }
        updateTransform(for: position, camera: camera)
    }
    
    // MARK: - Internal
    
    private func updateTransform(for position: SIMD3<Float>, camera: ARCamera?) {
        // Add to the list of recent positions.
        recentPreviewNodePositions.append(position)
        
        // Remove anything older than the last 8 positions.
        recentPreviewNodePositions.keepLast(8)
        
        // Move to average of recent positions to avoid jitter.
        if let average = recentPreviewNodePositions.average {
            simdPosition = average
        }
    }
}
Type Responsibility Depends on
ViewController Session configuration, preview setup and update, placement, relocalization, audio ARSCNView, PreviewNode, SCNAudioSource
PreviewNode Holds the model at half opacity and averages recent positions SCNNode, Utilities.swift helpers
ARSCNView.smartRaycast (extension) Three-step raycast: existing plane geometry, infinite plane near the object, then estimated planes ARSession.raycast

Observed: the sample defines no protocols of its own. Behavior is added by subclassing SCNNode and by extending ARSCNView, Array, RangeReplaceableCollection, and float4x4.

Access control

Symbol Access Verified effect Likely rationale
setUpCamera(), resetTracking(), beginRelocalization(), endRelocalization(), setUpPreviewNode(), updatePreviewNode() (AudioInARKit/ViewController.swift:93, AudioInARKit/ViewController.swift:172) private Callable only inside ViewController Inference: the delegate callbacks are the entry points; these are their steps.
restartExperience(_:) (AudioInARKit/ViewController.swift:183) @IBAction private Reachable from the storyboard button but not from other Swift types Inference: restart is a UI action only.
setUpAudio(), playSound() (AudioInARKit/ViewController.swift:290, AudioInARKit/ViewController.swift:299) private Audio setup is internal to the controller Inference: audio follows the placement lifecycle.
PreviewNode.recentPreviewNodePositions, updateTransform(for:camera:) (AudioInARKit/PreviewNode.swift:18, AudioInARKit/PreviewNode.swift:48) private Only update(for:planeAnchor:camera:) is the node’s interface Inference: hides the smoothing buffer.
raycastInfinitePlane, distanceToCamera (AudioInARKit/ARSCNView+Raycasts.swift:71, AudioInARKit/ARSCNView+Raycasts.swift:96) private Usable only inside the extension’s file Inference: smartRaycast is the single public-to-module entry point.
ViewController stored properties (AudioInARKit/ViewController.swift:22) implicit internal Accessible module-wide, though only the controller uses them Inference: default visibility in a one-module sample.

Reference code

AudioInARKit/ViewController.swift:105 — private reset used by the button and by session callbacks

    private func resetTracking() {
        let configuration = ARWorldTrackingConfiguration()
        configuration.planeDetection = .horizontal
        sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
        // Reset any placed object or live preview
        objectNode.removeFromParentNode()
        objectNode = SCNNode()
        previewNode?.removeFromParentNode()
        previewNode = nil
    }

The meaningful boundary is Swift private on helper methods: every state transition goes through a delegate callback or the restart action.

Logic ownership and placement

Logic Owning type or file Placement rationale
ARKit support check AppDelegate.applicationDidFinishLaunching(_:) Calls fatalError when world tracking is unsupported (AudioInARKit/AppDelegate.swift:15).
Camera and lighting setup ViewController.viewDidLoad() and setUpCamera() Disables automatic lighting and enables HDR on the point-of-view camera (AudioInARKit/ViewController.swift:51, AudioInARKit/ViewController.swift:99).
Session start ViewController.viewWillAppear(_:) Runs horizontal plane detection and computes screenCenter (AudioInARKit/ViewController.swift:68).
Preview creation ViewController.setUpPreviewNode() Loads firehead.scn, wraps it in PreviewNode, and pins world orientation with an SCNTransformConstraint (AudioInARKit/ViewController.swift:149).
Preview position ViewController.updatePreviewNode() and ARSCNView.smartRaycast Raycasts from the screen center only while tracking is .normal (AudioInARKit/ViewController.swift:175, AudioInARKit/ARSCNView+Raycasts.swift:14).
Placement and audio start renderer(_:didAdd:for:) First plane anchor while previewing (AudioInARKit/ViewController.swift:210).
Relocalization policy sessionShouldAttemptRelocalization(_:), beginRelocalization() Relocalize only when the object is placed; otherwise reset (AudioInARKit/ViewController.swift:282, AudioInARKit/ViewController.swift:119).
Orientation change viewWillTransition(to:with:) Recomputes screenCenter (AudioInARKit/ViewController.swift:85).

Design patterns

Pattern Source evidence Purpose or tradeoff
View-controller organization ViewController owns the audio source, nodes, and flags (AudioInARKit/ViewController.swift:22) and implements every callback The whole experience is one controller; there is no separate model type.
Delegate or data-source callbacks ARSCNViewDelegate adoption (AudioInARKit/ViewController.swift:12) with renderer and session callbacks (AudioInARKit/ViewController.swift:196, AudioInARKit/ViewController.swift:232) Framework events drive phase changes: preview, placement, relocalization, reset.

Naming conventions

  • Types: PreviewNode names the role plus the SceneKit base noun. The raycast file uses the Type+Feature.swift convention (ARSCNView+Raycasts.swift).
  • Methods: setUp… for one-time setup (setUpAudio, setUpCamera, setUpPreviewNode), update… for per-frame work (updatePreviewNode), and begin…/end… for paired transitions (beginRelocalization, endRelocalization).
  • Properties: nodes end in Node (objectNode, previewNode); booleans use is… (isRelocalizing, isRestartAvailable).
  • The project and folder names differ: Audio in ARKit.xcodeproj builds sources from AudioInARKit/.

Architecture takeaways

  • Positional audio needs no separate audio graph here: attaching an SCNAudioPlayer to the placed node lets SceneKit spatialize it from the node’s world position.
  • A node’s parent (objectNode.parent == nil) works as a compact phase flag between “previewing” and “placed”.
  • Relocalization handling is explicit and user-facing: hide content and mute audio while relocalizing, then restore both when tracking returns to normal.
  • smartRaycast packages a fallback strategy (exact plane, infinite plane near the object, estimated plane) behind one extension method.
  • Thread placement is left to the frameworks: callbacks mutate nodes and UI directly, and only the restart cooldown is explicitly scheduled on the main queue.

Source map

Source file Relevant symbols
AudioInARKit/ViewController.swift ViewController, setUpPreviewNode(), updatePreviewNode(), renderer(_:didAdd:for:), beginRelocalization(), playSound()
AudioInARKit/PreviewNode.swift PreviewNode, update(for:planeAnchor:camera:)
AudioInARKit/ARSCNView+Raycasts.swift smartRaycast, raycastInfinitePlane, distanceToCamera
AudioInARKit/AppDelegate.swift AppDelegate
AudioInARKit/Resources/Info.plist Scene manifest
Audio in ARKit.xcodeproj/project.pbxproj Deployment target, device family