Skip to main content

Playing Audio

Playing audio is made easy with AudioPlayerNode which is an audio graph source node.

Loading Audio

Instantiate an AudioPlayerNode, load the desired output, connect it to your graph and you are ready to play.

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

Streaming From a Local File

You can use streaming to load only parts of the audio file to memory. This can be useful for playing large files or to save memory in case its needed. Use stream() instead of load() to stream audio files from assets.

let path = Bundle.main.url(forResource: "example", withExtension: "mp3")!.path
...
audioPlayerNode.stream(path, withFormat: .mp3)

Streaming From URL

You can use the stream() function to play an audio file from the internet as well.

audioPlayerNode.stream("http://example.org/sound.wav", withFormat: .wav)

Playback Control

For controlling playback, you have the following functions:

  • play(): Starts playback from wherever the playhead is.
  • pause(): Pauses the playback.
  • stop(): Stops the playback and resets the playhead to the beginning of the audio data.

Looping

If you want your audio to play continuously (when it ends, restarts automatically), enable the isLoopingEnabled flag. This is set to false by default.

audioPlayerNode.isLoopingEnabled = true

tip

Take a look at the Audio Playback Example for further usage instructions.