Skip to content

Exports & events ​

Call exports as exports.np_audio:<name>(...). Volumes use 0..1, positions use seconds, all timestamps/durations/ramp lengths use milliseconds. getServerTime() returns the clock domain used by at and startedAt.

Server export calls derive ownership from GetInvokingResource(). Local names use letters, digits, _, ., or -, up to 64 characters. Registration IDs and handles are returned as owner:localId. Mutators accept your own local/full IDs. Foreign IDs return not_owner; guessing a handle grants no control. Catalog cues can be played by other trusted server resources using their full ID. Unqualified cues resolve in the caller's catalog first, then the default np_audio catalog. Client network requests require an explicit request policy.

Mutators return true, value? or false, reason. Getters return a copied table or nil; getCapabilities() and getServerTime() are read-only exceptions.

Cue definition ​

lua
{
    file = 'sounds/door.ogg', -- or url = 'https://media.example.com/door.ogg'
    resource = 'my_resource', -- file owner; defaults to registering resource
    backend = 'web', -- web | native | xsound | interact_sound | screens | custom name
    durationMs = 1500, -- required for files/native; trusted duration for autoplay
    category = 'sfx', -- sfx | music | dialogue | ambience | ui (configurable categories)
    spatial = true, loop = false, volume = 0.7, priority = 0,
    refDistance = 2.0, maxDistance = 30.0, falloff = 'linear',
    streamerSafe = false,
    effects = {
        occlusion = true, vehicle = true, water = true,
        lowpassHz = 22000, reverb = 0.1,
    },
    request = { enabled = false, ace = 'my_resource.sound', cooldownMs = 1000 },
}

For native, replace the file/URL with soundName and soundSet; native loops are rejected. For interact_sound, resource defaults to the configured InteractSound resource; set file = 'client/html/sounds/name.ogg'. Its asset is played through np_audio's owned player. screens is for URL music channel cues, not standalone play calls. Custom backend names are installed on each client through registerBackend.

Default limits: 256 total sources; 48 sources, 128 cues, 32 buses, 16 channels, 32 scenes and 32 filters per owner; 16 emitters per source/channel; 25 queued entries; 24 active client voices; 1000m maximum distance; 6h maximum duration and source retention. Global registration ceilings additionally cap cues at 2048, buses at 512, and channels at 128. Configure the primary limits in config/config.lua.

Missing files and files larger than 16 MiB fail registration. Files must also be in the owning resource's files manifest. HTTPS hosts must match the exact allowlist; credentials, custom ports, IP literals, localhost, private .local hosts, whitespace, and HTTP are rejected. Allowed public hosts and their redirect behavior remain the administrator's trust boundary; no URL is fetched on the np_audio server.

Playback options ​

lua
{
    coords = vec3(1, 2, 3), -- shorthand for one coordinate emitter
    -- or netId = <network id>, or emitters = {
    --   { coords = vec3(...), refDistance = 3, maxDistance = 50, gain = 1 },
    --   { netId = <network id>, refDistance = 3, maxDistance = 50, gain = 0.8 },
    -- }
    bucket = 0, -- defaults to first attached entity's bucket, otherwise 0
    interior = 123, -- optional exact interior ID; 0 means outdoors
    players = { 12, 38 }, -- optional server IDs, max 128, must be nonempty
    filter = 'staff', -- optional caller-owned registerAudienceFilter ID
    bus = 'machines', -- optional caller-owned bus ID
    volume = 0.7, priority = 5, at = exports.np_audio:getServerTime() + 150,
    position = 0, paused = false, loop = false,
    effects = { occlusion = true, vehicle = true, water = true, reverb = 0.1 },
}

Exactly one of coords/netId is required per emitter. Every attached entity must exist in the selected bucket. Entity positions follow locally when streamed in; an unresolved entity is silent, and a source loses its lifetime when all emitters disappear or leave their bucket. Nonspatial cues reject emitters and normally play to everyone in the selected bucket unless a player list/filter restricts them. Always target private UI cues explicitly or use playLocal.

Scheduling supports up to five minutes ahead. The server delivers state while clients prefetch and derive position from the shared clock. Cold asset loads, network latency, CEF scheduling, and streams without seeking can limit precision; this is synchronized playback, not sample-accurate distributed audio.

Server exports ​

Export Arguments and result
registerCue (id, definition, authorize?) -> ok, fullId/reason; authorize(player, fullCueId) must return exactly true for network requests
unregisterCue (id) -> ok, reason?; removes the catalog registration, not existing copied source definitions
play (cueId, options?) -> ok, handle/reason; preserves catalog loop setting unless overridden
playOneShot (cueId, options?) -> ok, handle/reason; always forces loop=false
stop (handle) -> ok, reason?; immediate release
pause, resume (handle) -> ok, reason?
seek (handle, seconds) -> ok, reason?; rejects invalid/out-of-duration positions for nonloops
setVolume (handle, volume, {rampMs?, at?}?) -> ok, reason?; ramp 0..60000ms, scheduled up to five minutes ahead
setEmitters (handle, emitters) -> ok, reason?; revalidates entities/bucket
setSourceBus (handle, busId?) -> ok, reason?; nil disconnects the bus
getSource (handle) -> copied source including cue, emitters, buses, clock anchors, ramp, revision, or nil; strips request/audience policy
stopAll () -> true, count; stops caller-owned sources and channel playback; keeps catalog/channel definitions and queues
createBus (id, {parent?, volume?, muted?}?) -> ok, fullId/reason; parent must belong to caller, depth <=8
setBusVolume (id, volume, {rampMs?, at?, muted?}?) -> ok, reason?; affects descendants
getBusState (id) -> copied bus or nil
destroyBus (id) -> ok, reason?; refuses buses with children or active source/channel references
registerAudienceFilter (id, fn) -> ok, fullId/reason; fn(player, sourceHandle) is synchronous, returns exactly true, fails closed on error
registerScene (id, entries) -> ok, fullId/reason; entries are {cue=..., options=...} and validated before registration
playScene (id, at?) -> ok, handles/reason; common start defaults to now+150ms; any creation failure rolls back the created scene sources
getServerTime () -> monotonic server time in ms
getCapabilities () -> {api=1, web, native, screens, xsound, interactSound, oneSync, maxSources}; screens means the channel API is available, not merely a running resource

Music channel exports (server) ​

Channels belong to the caller. A channel's volume multiplies its cue volume. The built-in backend supports the same emitters, audience filters, buses, preferences, and effects as ordinary sources. Queues contain catalog IDs; keep queued registrations available. Autoplay depends on trusted durationMs; unknown-duration streams continue until the owner skips/stops them.

Export Arguments and result
createChannel (id, options) -> ok, fullId/reason; playback options plus `backend='auto'
destroyChannel (id) -> ok, reason?; stops playback and destroys queue/host channel
channelLoad (id, cueId, {position?, paused?, at?}?) -> ok, reason?; replaces current media, preserves queue; default start now+150ms
channelPlay, channelResume (id) -> ok, reason?; resumes media or starts the first queued cue if idle
channelPause (id) -> ok, reason?
channelStop (id) -> ok, reason?; clears current media, keeps queue
channelSeek (id, seconds) -> ok, reason?
channelSkip (id) -> ok, reason?; plays queue head, or stops if empty
channelQueueAdd (id, cueId, mode?) -> ok, status/reason, queueLength?; mode end(default)/next/now; idle/now loads directly
channelQueueRemove (id, index) -> ok, reason?; 1-based
channelQueueMove (id, from, to) -> ok, reason?; 1-based
channelQueueClear (id) -> ok, reason?
channelSetVolume (id, volume, {rampMs?, at?}?) -> ok, reason?
channelSetEmitters (id, emitters, {interior?}?) -> ok, reason?
channelSetOptions (id, {loop?, autoAdvance?}) -> ok, reason?
crossfadeChannels (fromId, toId, newCueId, ms, {at?}?) -> ok, reason?; loads target at zero, ramps from to 0 and target to 1 on a common clock
getChannelState (id) -> copied channel, queue, current cue/backend/source, serverNow, and positionNow, or nil

For auto, a running, compatible np_screens host may own approved remote music. Restricted players/filters, nonspatial channels, and bundled files use np_audio. Forced screens with restricted audiences returns screens_audience_unsupported; the API never broadens the audience to satisfy a backend. Native/InteractSound legacy cues are not music channel backends; use web when registering the same file for channel playback.

Client exports ​

Export Arguments and result
requestCue (fullCueId, callback?) -> ok, requestId/reason; callback (ok, handle/reason) after approval; 5s timeout; bounded to 32 pending callbacks
playLocal (defaultCatalogCueId, {emitters?, coords?, volume?}?) -> ok, localHandle/reason; private configured audio; requires NUI/server clock ready
stopLocal (localHandle) -> ok, reason?; caller owns the local handle
setLocalVolume (categoryOrMaster, volume) -> ok, reason?; persists locally
setStreamerMode (boolean) -> ok, reason?; persists locally
getPreferences () -> copied {master, categories, streamer}
getActiveSources () -> map of locally rendered IDs to {backend,gain,distance,lowpassHz,error?}
getServerTime () -> estimated server clock in ms
getCapabilities () -> {api=1, backends={name={available, capabilities}}}
registerBackend (name, backend) -> ok, reason?; owner-tracked, cannot replace builtins/other owners

Custom backend callbacks: available() -> bool; start(source) -> voice; change(voice, source); update(voice, frame); stop(voice). frame contains now, gain, selected coords, local entity, lowpassHz, and reverb. capabilities is a descriptive table. Callbacks must be synchronous and fast; do not wait/yield in them. Stop must release every allocated handle/node. Exceptions are isolated and file/URL sources can fall back to Web Audio. Lifecycle removes backend registrations when their owning client resource stops.

Events and security ​

Local server events for integrations:

  • np_audio:ready({api, boot}) after config and addon host initialization.
  • np_audio:sourceStarted(handle, cueId, owner).
  • np_audio:sourceStopped(handle, reason, owner).
  • np_audio:channelChanged(fullId, currentCueId?, backend).
  • np_audio:channelError(fullId, reason).

Local client events:

  • np_audio:playbackStatus(handle, 'loaded'|'playing'|'ended') for built-in media.
  • np_audio:playbackError(handle, detail) for local playback failures.
  • np_audio:preferencesChanged(preferences).

Clients send only np_audio:requestCue(cueId, nonce), np_audio:ready() and np_audio:clock(nonce). These are implementation transport events; integrations should use exports. Requests are rate limited (8 per 5s by default), bounded, deduplicated over the last 64 nonces, and checked against cue enabled/ACE/ cooldown/authorization policy. The server derives ped network ID, routing bucket, and private targets. It never accepts client asset URLs, coordinates, volume, arbitrary target players, source controls, duration, or queue commands.

NUI observations remain local. A client reporting that media ended cannot skip shared playback. Clock/replay/window limits protect legitimate traffic; duplicate or denied requests do not automatically ban a player.

Snapshot reset/sequence/boot IDs prevent stale source resurrection. Asset paths and public metadata are visible to eligible recipients; do not put secrets in audio catalogs. Interior filtering and local mute are experience controls. Server-side audience/bucket/range checks are the delivery boundary.

Common failures: invalid_*, unknown_cue, not_found, not_owner, exists, missing_or_large_asset, missing_entity, entity_bucket_mismatch, source_limit, cue_limit, bus_limit, channel_limit, queue_full, denied, cooldown, cue_not_requestable, timeout, not_ready, unsupported_transport, unsupported_volume, unsupported_loop, channel_required, channel_backend_unsupported, screens_unavailable, screens_api_unavailable, screens_audience_unsupported, bus_has_children, bus_in_use, and position_past_end. Failed backend calls are returned rather than widening audiences or treating a missing host as a successful sound.