Reference

Audio Devices

palace.device_names: DeviceNames

Read-only namespace of device names by category (basic, full and capture), as tuples of strings whose first item being the default.

palace.query_extension(name: str) → bool

Return if a non-device-specific ALC extension exists.

See also

Device.query_extension()

Query ALC extension on a device

class palace.Device

Audio mix output, via either a system stream or a hardware port.

This can be used as a context manager that calls close upon completion of the block, even if an error occurs.

Parameters
  • name (str, optional) – The name of the playback device.

  • fallback (Iterable[str], optional) – Device names to fallback to, default to an empty tuple.

Raises

RuntimeError – If device creation fails.

Warns

RuntimeWarning – Before each fallback.

See also

device_names

Available device names

property alc_version

ALC version supported by this device.

property basic_name

Basic name of the device.

property clock_time

Current clock time for the device.

Notes

This starts relative to the device being opened, and does not increment while there are no contexts nor while processing is paused. Currently, this may not exactly match the rate that sources play at. In the future it may utilize an OpenAL extension to retrieve the audio device’s real clock.

close() → None

Close and free the device.

All previously-created contexts must first be destroyed.

property current_hrtf

Name of the HRTF currently being used by this device.

If HRTF is not currently enabled, this will be None.

property efx_version

EFX version supported by this device.

If the ALC_EXT_EFX extension is unsupported, this will be (0, 0).

property frequency

Playback frequency in hertz.

property hrtf_enabled

Whether HRTF is enabled on the device.

If the ALC_SOFT_HRTF extension is unavailable, this will return False although there could still be HRTF applied at a lower hardware level.

property hrtf_names

List of available HRTF names.

The order is retained from OpenAL, such that the index of a given name is the ID to use with ALC_HRTF_ID_SOFT.

If the ALC_SOFT_HRTF extension is unavailable, this will be an empty list.

property max_auxiliary_sends

Maximum number of auxiliary source sends.

If ALC_EXT_EFX is unsupported, this will be 0.

property name

Name of the device.

pause_dsp() → None

Pause device processing and stop contexts’ updates.

Multiple calls are allowed but it is not reference counted, so the device will resume after one resume_dsp call.

This requires the ALC_SOFT_pause_device extension.

query_extension(name: str) → bool

Return if an ALC extension exists on this device.

See also

query_extension()

Query non-device-specific ALC extension

reset(attrs: Dict[int, int]) → None

Reset the device, using the specified attributes.

If the ALC_SOFT_HRTF extension is unavailable, this will be a no-op.

resume_dsp() → None

Resume device processing and restart contexts’ updates.

Multiple calls are allowed and will no-op.

Audio Library Contexts

palace.CHANNEL_CONFIG: int

Context creation key to specify the channel configuration (either MONO, STEREO, QUAD, X51, X61 or X71).

palace.SAMPLE_TYPE: int

Context creation key to specify the sample type (either [UNSIGNED_]{BYTE,SHORT,INT} or FLOAT).

palace.FREQUENCY: int

Context creation key to specify the frequency in hertz.

palace.MONO_SOURCES: int

Context creation key to specify the number of mono (3D) sources.

palace.STEREO_SOURCES: int

Context creation key to specify the number of stereo sources.

palace.MAX_AUXILIARY_SENDS: int

Context creation key to specify the maximum number of auxiliary source sends.

palace.HRTF: int

Context creation key to specify whether to enable HRTF (either FALSE, TRUE or DONT_CARE).

palace.HRTF_ID: int

Context creation key to specify the HRTF to be used.

palace.OUTPUT_LIMITER: int

Context creation key to specify whether to use a gain limiter (either FALSE, TRUE or DONT_CARE).

palace.distance_models: Tuple[str, ...]

Names of available distance models.

palace.thread_local(state: bool) → Iterator[None]

Return a context manager controlling preference of local thread.

Effectively, it sets the fallback value for the thread argument for current_context and use_context.

Initially, globally current Context is preferred.

palace.current_context(thread: Optional[bool] = None) → Optional[palace.Context]

Return the context that is currently used.

If thread is set to True, return the thread-specific context used for OpenAL operations. This requires the non-device-specific as well as the context’s device ALC_EXT_thread_local_context extension to be available.

In case thread is not specified, fallback to preference made by thread_local.

palace.use_context(context: Optional[palace.Context], thread: Optional[bool] = None) → None

Make the specified context current for OpenAL operations.

This fails silently if the given context has been destroyed. In case thread is not specified, fallback to preference made by thread_local.

If thread is True, make the context current for OpenAL operations on the calling thread only. This requires the non-device-specific as well as the context’s device ALC_EXT_thread_local_context extension to be available.

class palace.Context

Container maintaining the audio environment.

Context contains the environment’s settings and components such as sources, buffers and effects.

This can be used as a context manager, e.g.

with context:
    ...

is equivalent to

previous = current_context()
use_context(context)
try:
    ...
finally:
    use_context(previous)
    context.destroy()
Parameters
  • device (Device) – The device on which the context is to be created.

  • attrs (Dict[int, int]) – Attributes specified for the context to be created.

Variables
  • device (Device) – The device this context was created from.

  • listener (Listener) – The listener instance of this context.

Raises

RuntimeError – If context creation fails.

async_wake_interval

Current interval used for waking up the background thread.

property available_resamplers

The list of resamplers supported by the context.

If the AL_SOFT_source_resampler extension is unsupported this will be an empty list, otherwise there would be at least one entry.

This method require the context to be current.

property default_resampler_index

The context’s default resampler index.

If the AL_SOFT_source_resampler extension is unsupported the resampler list will be empty and this will return 0.

If you try to access the resampler list with this index without extension, undefined behavior will occur (accessing an out of bounds array index).

This method require the context to be current.

destroy() → None

Destroy the context.

The context must not be current when this is called.

property distance_model

The model for source attenuation based on distance.

The default, ‘inverse clamped’, provides a realistic l/r reduction in volume (that is, every doubling of distance cause the gain to reduce by half).

The clamped distance models restrict the source distance for the purpose of distance attenuation, so a source won’t sound closer than its reference distance or farther than its max distance.

Raises

ValueError – If set to a preset cannot be found in distance_models.

property doppler_factor

Factor to apply to all source’s doppler calculations.

end_batch() → None

Continue processing the context and end batching.

is_supported(channel_config: str, sample_type: str) → bool

Return if the channel config and sample type is supported.

This method require the context to be current.

See also

sample_types()

Set of sample types

channel_configs()

Set of channel configurations

message_handler

Handler of some certain events.

property speed_of_sound

The speed of sound propagation in units per second.

It is used to calculate the doppler effect along with other distance-related time effects.

The default is 343.3 units per second (a realistic speed assuming 1 meter per unit). If this is adjusted for a different unit scale, Listener.meters_per_unit should also be adjusted.

start_batch() → None

Suspend the context to start batching.

update() → None

Update the context and all sources belonging to this context.

class palace.Listener

Listener instance of the given context.

It is recommended that applications access the listener via Context.listener, which avoid the overhead caused by the creation of the wrapper object.

Parameters

context (Optional[Context], optional) – The context on which the listener instance is to be created. By default current_context() is used.

Raises

RuntimeError – If there is neither any context specified nor current.

property gain

Master gain for all context output.

property meters_per_unit

Number of meters per unit.

This is used for various effects relying on the distance in meters including air absorption and initial reverb decay. If this is changed, so should the speed of sound (e.g. context.speed_of_sound = 343.3 / meters_per_unit to maintain a realistic 343.3 m/s for sound propagation).

property orientation

3D orientation of the listener.

Parameters
  • at (Tuple[float, float, float]) – Relative position.

  • up (Tuple[float, float, float]) – Relative direction.

property position

3D position of the listener.

property velocity

3D velocity of the listener, in units per second.

As with OpenAL, this does not actually alter the listener’s position, and instead just alters the pitch as determined by the doppler effect.

class palace.MessageHandler

Message handler interface.

Applications may derive from this and set an instance on a context to receive messages. The base methods are no-ops, so subclasses only need to implement methods for relevant messages.

Exceptions raised from MessageHandler instances are ignored.

buffer_loading(name: str, channel_config: str, sample_type: str, sample_rate: int, data: Sequence[int]) → None

Handle messages from Buffer initialization.

This is called when a new buffer is about to be created and loaded. which may be called asynchronously for buffers being loaded asynchronously.

Parameters
  • name (str) – Resource name passed to Buffer.

  • channel_config (str) – Channel configuration of the given audio data.

  • sample_type (str) – Sample type of the given audio data.

  • sample_rate (int) – Sample rate of the given audio data.

  • data (MutableSequence[int]) –

    The audio data that is about to be fed to the OpenAL buffer.

    It is a mutable memory array of signed 8-bit integers, following Python buffer protocol.

device_disconnected(device: palace.Device) → None

Handle disconnected device messages.

This is called when the given device has been disconnected and is no longer usable for output. As per the ALC_EXT_disconnect specification, disconnected devices remain valid, however all playing sources are automatically stopped, any sources that are attempted to play will immediately stop, and new contexts may not be created on the device.

Notes

Connection status is checked during Context.update calls, so method must be called regularly to be notified when a device is disconnected. This method may not be called if the device lacks support for the ALC_EXT_disconnect extension.

resource_not_found(name: str) → str

Return the fallback resource for the one of the given name.

This is called when name is not found, allowing substitution of a different resource until the returned string either points to a valid resource or is empty (default).

For buffers being cached, the original name will still be used for the cache entry so one does not have to keep track of substituted resource names.

source_force_stopped(source: palace.Source) → None

Handle forcefully stopped sources.

This is called when the given source was forced to stop, because of one of the following reasons:

  • There were no more mixing sources and a higher-priority source preempted it.

  • source is part of a SourceGroup (or sub-group thereof) that had its SourceGroup.stop_all method called.

  • source was playing a buffer that’s getting removed.

source_stopped(source: palace.Source) → None

Handle end-of-buffer/stream messages.

This is called when the given source reaches the end of buffer or stream, which is detected upon a call to Context.update.

Resource Caching

palace.cache(names: Iterable[str], context: Optional[palace.Context] = None) → None

Cache given audio resources asynchronously.

Duplicate names and buffers already cached are ignored. Cached buffers must be freed before destroying the context.

The resources will be scheduled for caching asynchronously, and should be retrieved later when needed by initializing Buffer corresponding objects. Resources that cannot be loaded, for example due to an unsupported format, will be ignored and a later Buffer initialization will raise an exception.

If context is not given, current_context() will be used.

Raises

RuntimeError – If there is neither any context specified nor current.

See also

free()

Free cached audio resources given their names

Buffer.destroy()

Free the buffer’s cache

palace.free(names: Iterable[str], context: Optional[palace.Context] = None) → None

Free cached audio resources given their names.

If context is not given, current_context() will be used.

Raises

RuntimeError – If there is neither any context specified nor current.

class palace.Buffer

Buffer of preloaded PCM samples coming from a Decoder.

Cached buffers must be freed using destroy before destroying context. Alternatively, this can be used as a context manager that calls destroy upon completion of the block, even if an error occurs.

Parameters
  • name (str) – Audio file or resource name. Multiple calls with the same name will return the same buffer.

  • context (Optional[Context], optional) – The context from which the buffer is to be created and cached. By default current_context() is used.

Variables

name (str) – Audio file or resource name.

Raises

RuntimeError – If there is neither any context specified nor current.

property channel_config

Buffer’s sample configuration.

destroy() → None

Free the buffer’s cache.

This invalidates all other Buffer objects with the same name.

property frequency

Buffer’s frequency in hertz.

static from_decoder(decoder: palace.Decoder, name: str, context: Optional[palace.Context])palace.Buffer

Return a buffer created by reading the given decoder.

Parameters
  • decoder (Decoder) – The decoder from which the buffer is to be cached.

  • name (str) – The name to give to the buffer. It may alias an audio file, but it must not currently exist in the buffer cache.

  • context (Optional[Context], optional) – The context from which the buffer is to be created. By default current_context() is used.

Raises

RuntimeError – If there is neither any context specified nor current; or if name is already used for another buffer.

property length

Length of the buffer in sample frames.

property length_seconds

Length of the buffer in seconds.

loop_points

Loop points for looping sources.

If the AL_SOFT_loop_points extension is not supported by the current context, start = 0 and end = length respectively. Otherwise, start < end <= length.

Parameters
  • start (int) – Starting point, in sample frames (inclusive).

  • end (int) – Ending point, in sample frames (exclusive).

Notes

The buffer must not be in use when this property is set.

play(source: Optional[palace.Source])palace.Source

Play source using the buffer.

Return the source used for playing. If None is given, create a new one.

One buffer may be played from multiple sources simultaneously.

property sample_type

Buffer’s sample type.

property size

Storage size used by the buffer, in bytes.

Notes

The size in bytes may not be what you expect from the length, as it may take more space internally than the channel_config and sample_type suggest.

property source_count

Number of sources currently using the buffer.

Notes

Context.update needs to be called to reliably ensure the count is kept updated for when sources reach their end. This is equivalent to calling len(self.sources).

property sources

Source objects currently playing the buffer.

Sources & Source Groups

class palace.Source

Sound source for playing audio.

There is no practical limit to the number of sources one may create.

When the source is no longer needed, destroy must be called, unless the context manager is used, which guarantees the source’s destructioni upon completion of the block, even if an error occurs.

Parameters

context (Optional[Context], optional) – The context from which the source is to be created. By default current_context() is used.

Raises

RuntimeError – If there is neither any context specified nor current.

air_absorption_factor

Multiplier for atmospheric high-frequency absorption

Its value ranging from 0 to 10. A factor of 1 results in a nominal -0.05 dB per meter, with higher values simulating foggy air and lower values simulating dryer air; default to 0.

cone_angles

Cone inner and outer angles in degrees.

Parameters
  • inner (float) – The area within which the listener will hear the source without extra attenuation, default to 360.

  • outer (float) – The area outside of which the listener will hear the source attenuated according to outer_cone_gains, default to 360.

Raises

ValueError – If set to a value where inner is greater than outer or either of them is outside of the [0, 360] interval.

Notes

The areas follow the facing direction, so for example an inner angle of 180 means the entire front face of the source is in the inner cone.

destroy() → None

Destroy the source, stop playback and release resources.

distance_range

Reference and maximum distance for current distance model.

For Clamped distance models, the source’s calculated distance is clamped to the specified range before applying distance-related attenuation.

Parameters
  • refdist (float) – The distance at which the source’s volume will not have any extra attenuation (an effective gain multiplier of 1), default to 0.

  • maxdist (float) – The maximum distance, default to FLT_MAX, which is the maximum value of a single-precision floating-point variable (2**128 - 2**104).

Raises

ValueError – If set to a value where refdist is greater than maxdist or either of them is outside of the [0, FLT_MAX] interval.

doppler_factor

The doppler factor for the doppler effect’s pitch shift.

This effectively scales the source and listener velocities for the doppler calculation.

Raises

ValueError – If set to a value outside of the [0, 1] interval.

fade_out_to_stop(gain: float, ms: int) → None

Fade the source to gain over ms milliseconds.

gain is in addition to the base gain and must be within the [0, 1] interval. ms must be positive.

The fading is logarithmic. As a result, the initial drop-off may happen faster than expected but the fading is more perceptually consistant over the given duration. It will take just as much time to go from -6 dB to -12 dB as it will to go from -40 dB to -46 dB, for example.

Fading is updated during calls to Context.update, which should be called regularly (30 to 50 times per second) for the fading to be smooth.

property filter

Linear gains on the direct path signal, clamped to [0, 1].

Parameters
  • gain (float) – Linear gain applying to all frequencies, default to 1.

  • gain_hf (float) – Linear gain applying to high frequencies, default to 1.

  • gain_lf (float) – Linear gain applying to low frequencies, default to 1.

gain

Base linear volume gain, default to 1.0.

Raises

ValueError – If set to a negative value.

gain_auto

Whether automatically adjust gains.

Respectively for direct path’s high frequency gain, send paths’ gain and send paths’ high-frequency gain are automatically adjusted. The default is True for all.

gain_range

The range which the source’s gain is clamped to.

This is used after distance and cone attenuation are applied to the gain base and before the adjustments of the filter gain.

Parameters
  • mingain (float) – Minimum gain, default to 0.

  • maxgain (float) – Maximum gain, default to 1.

Raises

ValueError – If set to a value where mingain is greater than maxgain or either of them is outside of the [0, 1] interval.

group

Parent group of this source.

The parent group influences all sources that belong to it. A source may only be the child of one SourceGroup at a time, although that source group may belong to another source group.

This is None when the source does not belong to any group. On the other hand, setting it to None removes the source from its current group.

See also

SourceGroup

A group of Source references

property latency

Source latency in nanoseconds.

If the AL_SOFT_source_latency extension is unsupported, the latency will be 0.

property latency_seconds

Source latency in seconds.

If the AL_SOFT_source_latency extension is unsupported, the latency will be 0.

looping

Whether the source should loop.

The loop points are determined by the playing buffer or decoder.

offset

Source offset in sample frames. For streaming sources this will be the offset based on the decoder’s read position.

property offset_seconds

Source offset in seconds.

For streaming sources this will be the offset based on the decoder’s read position.

orientation

3D orientation of the source.

Parameters
  • at (Tuple[float, float, float]) – Relative position.

  • up (Tuple[float, float, float]) – Relative direction.

Notes

Unlike the AL_EXT_BFORMAT extension this property comes from, this also affects the facing direction.

outer_cone_gains

Gain when listener is out of the source’s outer cone area.

Parameters
  • gain (float) – Linear gain applying to all frequencies, default to 1.

  • gain_hf (float) – Linear gain applying extra attenuation to high frequencies creating a low-pass effect, default to 1. It has no effect without the ALC_EXT_EFX extension.

Raises

ValueError – If either of the gains is set to a value outside of the [0, 1] interval.

pause() → None

Pause the source if it is playing.

property paused

Whether the source is currently paused.

pitch

Linear pitch shift base, default to 1.0.

Raises

ValueError – If set to a nonpositive value.

property playing

Whether the source is currently playing.

position

3D position of the source.

priority

Playback priority (natural number).

The lowest priority sources will be forcefully stopped when no more mixing sources are available and higher priority sources are played.

radius

Radius of the source, as if it is a sound-emitting sphere.

This has no effect without the AL_EXT_SOURCE_RADIUS extension.

Raises

ValueError – If set to a negative value.

relative

Whether the source’s 3D parameters are relative to listener.

The affected parameters includes position, velocity, and orientation.

resampler_index

Index of the resampler to use for this source.

The index must be nonnegative, from the resamplers returned by Context.get_available_resamplers, and has no effect without the AL_SOFT_source_resampler extension.

resume() → None

Resume the source if it is paused.

rolloff_factors

Rolloff factor and room factor for the direct and send paths.

This is effectively a distance scaling relative to the reference distance.

Raises

ValueError – If either of rolloff factors is set to a negative value.

Notes

To disable distance attenuation for send paths, set room factor to 0. The reverb engine will, by default, apply a more realistic room decay based on the reverb decay time and distance.

property sends

Collection of send path signals.

Send paths can be retrieved using a nonnegative index, which has no effect if not less than the device’s max_auxiliary_sends.

Each send path has two write-only descriptors, effect and filter.

Examples

>>> source.sends[0].effect = effect
>>> source.sends[1].filter = 1, 0.6, 0.9
spatialize

Whether to enable 3D spatialization.

Either True (the source always has 3D spatialization features), False (never has 3D spatialization features), or None (spatialization is enabled based on playing a mono sound or not, default).

This has no effect without the AL_SOFT_source_spatialize extension.

stereo_angles

Left and right channel angles, in radians.

The angles go counter-clockwise, with 0 being in front and positive values going left.

This is only used for stereo playback and has no effect without the AL_EXT_STEREO_ANGLES extension.

stop() → None

Stop playback, releasing the buffer or decoder reference.

velocity

3D velocity in units per second.

As with OpenAL, this does not actually alter the source’s position, and instead just alters the pitch as determined by the doppler effect.

class palace.SourceGroup

A group of Source references.

For instance, setting SourceGroup.gain to 0.5 will halve the gain of all sources in the group.

This can be used as a context manager that calls destroy upon completion of the block, even if an error occurs.

Parameters

context (Optional[Context], optional) – The context from which the source group is to be created. By default current_context() is used.

Raises

RuntimeError – If there is neither any context specified nor current.

destroy() → None

Destroy the source group, remove and free all sources.

gain

Source group gain.

This accumulates with its sources’ and sub-groups’ gain.

parent_group

The source group this source group is a child of.

Raises

RuntimeException – If this group is being added to its sub-group (i.e. it would create a circular sub-group chain).

pause_all() → None

Pause all currently-playing sources under this group.

This is done recursively, including sub-groups.

pitch

Source group pitch.

This accumulates with its sources’ and sub-groups’ pitch.

resume_all() → None

Resume all currently-playing sources under this group.

This is done recursively, including sub-groups.

property sources

Sources under this group.

stop_all() → None

Stop all currently-playing sources under this group.

This is done recursively, including sub-groups.

property sub_groups

Source groups under this group.

Environmental Effects

For the sake of brevity, we only document the constraints of each effect’s properties. Further details can be found at OpenAL’s Effect Extension Guide which specifies the purpose and usage of each value.

palace.reverb_preset_names: Tuple[str, ...]

Names of predefined reverb effect presets in lexicographical order.

class palace.BaseEffect

Base effect processor.

Instances of this class has no effect (pun intended).

It takes the output mix of zero or more sources, applies DSP for the desired effect, then adds to the output mix.

This can be used as a context manager that calls destroy upon completion of the block, even if an error occurs.

Parameters

context (Optional[Context], optional) – The context from which the effect is to be created. By default current_context() is used.

Raises

RuntimeError – If there is neither any context specified nor current.

See also

ReverbEffect

EAXReverb effect

ChorusEffect

Chorus effect

destroy() → None

Destroy the effect slot, returning it to the system.

If the effect slot is currently set on a source send, it will be removed first.

property slot_gain

Gain of the effect slot.

property source_sends

List of sources using this effect and their pairing sends.

property use_count

Number of source sends the effect slot is used by.

This is equivalent to calling len(self.source_sends).

class palace.ReverbEffect

EAXReverb effect.

It will automatically downgrade to the Standard Reverb effect if EAXReverb effect is not supported.

Parameters
  • preset (str, optional) – The initial preset to start with, falling back to GENERIC.

  • context (Optional[Context], optional) – The context from which the effect is to be created. By default current_context() is used.

Raises
  • ValueError – If the specified preset cannot be found in reverb_preset_names.

  • RuntimeError – If there is neither any context specified nor current.

air_absorption_gain_hf

High frequency air absorption gain, from 0.892 to 1.0.

decay_hf_limit

High frequency decay limit.

decay_hf_ratio

High frequency decay ratio, from 0.1 to 20.0.

decay_lf_ratio

Low frequency decay ratio, from 0.1 to 20.0.

decay_time

Decay time, from 0.1 to 20.0.

density

Density, from 0.0 to 1.0.

diffusion

Diffusion, from 0.0 to 1.0.

echo_depth

Echo depth, from 0.0 to 1.0.

echo_time

Echo time, from 0.075 to 0.25.

gain

Gain, from 0.0 to 1.0.

gain_hf

High frequency gain, from 0.0 to 1.0.

gain_lf

Low frequency gain, from 0.0 to 1.0.

hf_reference

High frequency reference, from 1000.0 to 20000.0.

late_reverb_delay

Late reverb delay, from 0.0 to 0.1.

late_reverb_gain

Late reverb gain, from 0.0 to 10.0.

late_reverb_pan

Late reverb as 3D vector of magnitude between 0 and 1.

lf_reference

Low frequency reference, from 20.0 to 1000.0.

modulation_depth

Modulation depth, from 0.0 to 1.0.

modulation_time

Modulation time, from 0.004 to 4.0.

reflections_delay

Reflections delay, from 0.0 to 0.3.

reflections_gain

Reflections gain, from 0.0 to 3.16.

reflections_pan

Reflections as 3D vector of magnitude between 0 and 1.

room_rolloff_factor

Room rolloff factor, from 0.0 to 10.0.

property send_auto

Whether to automatically adjust send slot gains.

class palace.ChorusEffect

Chorus effect.

Parameters
  • waveform (str) – Either ‘sine’ or ‘triangle’.

  • phase (int) – From -180 to 180.

  • depth (float) – From 0.0 to 1.0.

  • feedback (float) – From -1.0 to 1.0.

  • delay (float) – From 0.0 to 0.016.

  • context (Optional[Context], optional) – The context from which the effect is to be created. By default current_context() is used.

Raises

RuntimeError – If there is neither any context specified nor current.

delay

Delay, from 0.0 to 0.016.

depth

Depth, from 0.0 to 1.0.

feedback

Feedback, from -1.0 to 1.0.

phase

Phase, from -180 to 180.

waveform

Waveform, either ‘sine’ or ‘triangle’.

Decoder Interface

palace.sample_types: Tuple[str, ...]

Names of available sample types.

palace.channel_configs: Tuple[str, ...]

Names of available channel configurations.

palace.decoder_factories: DecoderNamespace

Simple object for storing decoder factories.

User-registered factories are tried one after another if RuntimeError is raised, in lexicographical order. Internal decoder factories are always used after registered ones.

palace.decode(name: str, context: Optional[palace.Context] = None)palace.Decoder

Return the decoder created from the given resource name.

This first tries user-registered decoder factories in lexicographical order, then fallback to the internal ones.

Raises

RuntimeError – If there is neither any context specified nor current.

See also

decoder_factories()

Simple object for storing decoder factories

palace.sample_size(length: int, channel_config: str, sample_type: str) → int

Return the size of the given number of sample frames.

Raises
  • ValueError – If either channel_config or sample_type is invalid.

  • RuntimeError – If the byte size result too large.

palace.sample_length(size: int, channel_config: str, sample_type: str) → int

Return the number of frames stored in the given byte size.

Raises

ValueError – If either channel_config or sample_type is invalid.

class palace.Decoder

Generic audio decoder.

Parameters
  • name (str) – Audio file or resource name.

  • context (Optional[Context], optional) – The context from which the decoder is to be created. By default current_context() is used.

Raises

RuntimeError – If there is neither any context specified nor current.

See also

Buffer

Preloaded PCM samples coming from a Decoder

Notes

Due to implementation details, while this creates decoder objects from filenames using contexts, it is the superclass of the ABC (abstract base class) BaseDecoder. Because of this, Decoder may only initialize an internal one. To use registered factories, please call the module-level decode function instead.

property channel_config

Channel configuration of the audio being decoded.

property frequency

Sample frequency, in hertz, of the audio being decoded.

property length

Length of audio in sample frames, falling-back to 0.

Notes

Zero-length decoders may not be used to load a Buffer.

property length_seconds

Length of audio in seconds, falling-back to 0.0.

Notes

Zero-length decoders may not be used to load a Buffer.

property loop_points

Loop points in sample frames.

Parameters
  • start (int) – Inclusive starting loop point.

  • end (int) – Exclusive starting loop point.

Notes

If start >= end, all available samples are included in the loop.

play(chunk_len: int, queue_size: int, source: Optional[palace.Source])palace.Source

Stream audio asynchronously from the decoder.

The decoder must NOT have its read or seek called from elsewhere while in use.

Parameters
  • chunk_len (int) – The number of sample frames to read for each chunk update. Smaller values will require more frequent updates and larger values will handle more data with each chunk.

  • queue_size (int) – The number of chunks to keep queued during playback. Smaller values use less memory while larger values improve protection against underruns.

  • source (Optional[Source], optional) – The source object to play audio. If None is given, a new one will be created from the current context.

Returns

Return type

The source used for playing.

read(count: int) → bytes

Decode and return count sample frames.

If less than the requested count samples is returned, the end of the audio has been reached.

See also

sample_length()

length of samples of given size

property sample_type

Sample type of the audio being decoded.

seek(pos: int) → bool

Seek to pos, specified in sample frames.

Return if the seek was successful.

class palace.BaseDecoder

Audio decoder interface.

Applications may derive from this, implement necessary methods, and use it in places the API wants a BaseDecoder object.

Exceptions raised from BaseDecoder instances are ignored.

abstract property channel_config

Channel configuration of the audio being decoded.

abstract property frequency

Sample frequency, in hertz, of the audio being decoded.

abstract property length

Length of audio in sample frames, falling-back to 0.

Notes

Zero-length decoders may not be used to load a Buffer.

abstract property loop_points

Loop points in sample frames.

Parameters
  • start (int) – Inclusive starting loop point.

  • end (int) – Exclusive starting loop point.

Notes

If start >= end, all available samples are included in the loop.

abstract read(count: int) → bytes

Decode and return count sample frames.

If less than the requested count samples is returned, the end of the audio has been reached.

abstract property sample_type

Sample type of the audio being decoded.

abstract seek(pos: int) → bool

Seek to pos, specified in sample frames.

Return if the seek was successful.

File I/O Interface

palace.current_fileio() → Optional[Callable[[str], palace.FileIO]]

Return the file I/O factory currently in used by audio decoders.

If the default is being used, return None.

palace.use_fileio(factory: Optional[Callable[[str], FileIO]], buffer_size: int = 8192) → None

Set the file I/O factory instance to be used by audio decoders.

If factory=None is provided, revert to the default.

class palace.FileIO(*args, **kwargs)

File I/O protocol.

This static duck type defines methods required to be used by palace decoders. Despite its name, a FileIO is not necessarily created from a file, but any seekable finite input stream.

Many classes defined in the standard library module io are compatible with this protocol.

Notes

Since PEP 544 is only implemented in Python 3.8+, type checking for this on earlier Python version might not work as expected.

abstract close() → None

Close the file.

abstract read(size: int) → bytes

Read at most size bytes, returned as bytes.

abstract seek(offset: int, whence: int = 0) → int

Move to new file position and return the file position.

Parameters
  • offset (int) – A byte count.

  • whence (int, optional) – Either 0 (default, move relative to start of file), 1 (move relative to current position) or 2 (move relative to end of file).