Skip to content

Audio

A sound is a Source. You load one from a file and then play it, pause it, change its volume and so on. Loading takes a kind: a static source decodes all the way into memory, which suits short effects you play often, and a streaming source decodes as it plays, which suits music. WAV, OGG, MP3, FLAC and tracker files all work, since SDL_mixer does the decoding.

let music = n2d.newSource("music.ogg", stStream)  # (1)!
let shot = n2d.newSource("shot.wav", stStatic)    # (2)!
music.setLooping(true)                            # (3)!
music.play()                                      # (4)!
  1. Load music as a streaming source, decoded as it plays.
  2. Load a short effect as a static source, decoded fully into memory.
  3. Make it repeat when it reaches the end.
  4. Start it.

The controls are what you would expect. play starts a source, or restarts it if it is already going, pause and resume hold and continue it, stop ends it and rewinds, and rewind and seek move the position, with tell reporting it in seconds. isPlaying and isPaused report the state, and duration is the length in seconds.

setVolume sets a source's loudness, 0 silent to 1 full, with values above 1 amplifying. setPitch changes its pitch, which also changes its speed since the two move together, and setLooping decides whether it repeats. When a source is done for good, destroy stops it and frees its data.

For positional sound, setPosition places a source in space so it pans left or right and fades with distance, and clearPosition turns that off. The listener sits at the origin by default, setListenerPosition moves it, which shifts every positioned source to match, and getListenerPosition reads it back. On the engine itself, setVolume is the master volume over everything and stopAll stops every source at once.

shot.setPosition(playerX - enemyX, 0)
shot.play()

If the machine has no audio device, which is the usual case on a build server, audio quietly turns itself off and every call here does nothing, so the same code still runs. audioAvailable tells you whether sound is on.

See also

The runnable audio example, and the audio API reference.