Skip to main content

Audio Playback

About Audio Playback

Audio playback refers to the process of playing back recorded audio files. This can be either loaded from memory or streamed from a file or a web-based audio stream. Audio playback is an essential part of many industries, including music, film, and broadcasting. It allows for the reproduction of sound in a way that is faithful to the original recording, allowing listeners to experience the full range of sounds and nuances in the recording.

Audio Player

This example loads an mp3 audio file and plays it on the audio output using AudioPlayerNode. Playback can be controlled by the play(), pause() and stop() methods.

Code Example

{
"nodes": {
{ "id": "audioPlayerNode", "type": "AudioPlayerNode" },
},
"connections": {
{ "sourceNode": "audioPlayerNode", "destinationNode": "outputNode" }
},
"tracks": {
"audioPlayerNode": "example.mp3"
}
}

Synchronized Audio Players

In this example two audio players are synchronized using a subgraph. The SubgraphSourceNode makes sure that the audio players are started and stopped exactly at the same time.

Code Example

import SwitchboardSDK

class SynchronizedAudioPlayersExample {
let audioEngine = SBAudioEngine()
let audioGraph = SBAudioGraph()
let subgraphNode = SBSubgraphProcessorNode()
let internalAudioGraph = SBAudioGraph()
let drumsPlayerNode = SBAudioPlayerNode()
let bassPlayerNode = SBAudioPlayerNode()
let mixerNode = SBMixerNode()

init() {
drumsPlayerNode.loadFile("drums.mp3")
bassPlayerNode.loadFile("bass.mp3")

internalAudioGraph.addNode(drumsPlayerNode)
internalAudioGraph.addNode(bassPlayerNode)
internalAudioGraph.addNode(mixerNode)

internalAudioGraph.connect(drumsPlayerNode, to: mixerNode)
internalAudioGraph.connect(bassPlayerNode, to: mixerNode)
internalAudioGraph.connect(mixerNode, to: internalAudioGraph.outputNode)

subgraphNode.setAudioGraph(internalAudioGraph)

audioGraph.addNode(subgraphNode)

audioGraph.connect(subgraphNode, to: audioGraph.outputNode)

audioEngine.start(audioGraph)
}

func play() {
// The audio players won't start playing until the internal audio graph is started
drumsPlayerNode.play()
bassPlayerNode.play()
internalAudioGraph.start()
}

func pause() {
// Stopping the internal audio graph first to make sure that both audio players are stopped at the same time
internalAudioGraph.stop()
drumsPlayerNode.pause()
bassPlayerNode.pause()
}

func stop() {
// Stopping the internal audio graph first to make sure that both audio players are stopped at the same time
internalAudioGraph.stop()
drumsPlayerNode.pause()
bassPlayerNode.pause()
}

func loadBass(url: String, format: SBCodec) {
drumsPlayerNode.load(url, withFormat: format) }

func loadDrums(url: String, format: SBCodec) {
bassPlayerNode.load(url, withFormat: format)
}
}