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.
- Swift
- Kotlin
import SwitchboardSDK
...
let audioPlayerNode = SBAudioPlayerNode()
...
let path = Bundle.main.url(forResource: "example", withExtension: "mp3")!.path
audioPlayerNode.load(path, withFormat: .mp3)
...
import com.synervoz.switchboard.sdk.Codec
import com.synervoz.switchboard.sdk.audiographnodes.AudioPlayerNode
...
private val audioPlayerNode = AudioPlayerNode()
...
val audioData: ByteArray = AssetLoader.load(requireContext(), "example.mp3")
audioPlayerNode.load(audioData, Codec.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.
- Swift
- Kotlin
let path = Bundle.main.url(forResource: "example", withExtension: "mp3")!.path
...
audioPlayerNode.stream(path, withFormat: .mp3)
audioPlayerNode.stream("example.mp3", Codec.MP3)
Streaming From URL
You can use the stream()
function to play an audio file from the internet as well.
- Swift
- Kotlin
audioPlayerNode.stream("http://example.org/sound.wav", withFormat: .wav)
audioPlayerNode.stream("http://example.org/sound.wav", Codec.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.
- Swift
- Kotlin
audioPlayerNode.isLoopingEnabled = true
audioPlayerNode.isLoopingEnabled = true
Take a look at the Audio Player Example for further usage instructions.