Binaural (3D)

How to configure binaural spatialization in real time

This example demonstrates how to apply an HRTF database to achieve binaural spatialization, creating a three-dimensional environment where the positions of the listener and source determine the output. The database can also be loaded asynchronously.

// Configure the graph for rendering
let context = Assembler(rendering: .live).createAudioGraph()

// Configure an audio source (Renderer) from a local audio file
let url = URL(fileURLWithPath: "/path/to/source.wav")
let source = FileRenderer(contentsOf: url)

// Configure the database from a local location
let url = URL(fileURLWithPath: "/path/to/database")
let database = BinauralDatabase(location: url, sampleRate: databaseSampleRate)
let _ = database.loadSynchronously()

// Configure a binaural spatializer and parameters
let destination = Binaural(database: database)
destination.position = .init(x: 0, y: 0, z: 0)
context.listener.up = Vector3<Float64>(x: 0, y: 1.0, z: 0)
context.listener.position = Vector3<Float64>(x: 0.0, y: 0.0, z: 0.0)
context.listener.forward = Vector3<Float64>(x: 0, y: 0, z: -1.0)

// Configure node connections
try context.connect(source: source, to: destination)
try context.connect(source: destination, to: context.destination)
source.play(after: 0)

The following video shows the sample code in action and its real-time processing.

circle-info

For a complete description of each class, method, and property referenced in this section, refer to the official API documentationarrow-up-right, where you will find detailed references, available components, parameters, and additional usage code examples.

Last updated