palace/html/reference.html

87 KiB
Raw Blame History

<html xmlns="http://www.w3.org/1999/xhtml"> <head> </head>

Reference

Pythonic Audio Library and Codecs Environment

palace.Vector3

Tuple of three floats.

Type

Type

palace.CHANNEL_CONFIG

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

Type

int

palace.SAMPLE_TYPE

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

Type

int

palace.FREQUENCY

Context creation key to specify the frequency in hertz.

Type

int

palace.MONO_SOURCES

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

Type

int

palace.STEREO_SOURCES

Context creation key to specify the number of stereo sources.

Type

int

palace.MAX_AUXILIARY_SENDS

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

Type

int

palace.HRTF

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

Type

int

palace.HRTF_ID

Context creation key to specify the HRTF to be used.

Type

int

palace.OUTPUT_LIMITER

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

Type

int

palace.sample_types

Names of available sample types.

Type

Tuple[str, ..]

palace.channel_configs

Names of available channel configurations.

Type

Tuple[str, ..]

palace.device_names

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

Type

DeviceNames

palace.decoder_factories

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.

Type

DecoderNamespace

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

Return the size of the given number of sample frames.

Raises

RuntimeError If the byte size result too large.

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

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

palace.query_extension(str name: str) → bool

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

See also

Device.query_extension()

Query ALC extension on a device

palace.current_context(thread: bool = False) → Optional[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 contexts device ALC_EXT_thread_local_context extension to be available.

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

Make the specified context current for OpenAL operations.

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

See also

Context()

Audio environment container

palace.current_fileio() → Optional[Callablestr], 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[Callablestr], FileIO, buffer_size: int = DEFAULT_BUFFER_SIZE) → 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.Device(str name: str = '', fallback: Iterable[str] = ()) → None

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 devices real clock.

close(self) → 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(self) → 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(self, str name: str) → bool

Return if an ALC extension exists on this device.

See also

query_extension()

Query non-device-specific ALC extension

reset(self, 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(self) → None

Resume device processing and restart contexts updates.

Multiple calls are allowed and will no-op.

class palace.Context(Device device: Device, attrs: Dict[int, int] = {}) → None

Container maintaining the entire audio environment, its 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.

device

The device this context was created from.

Type

Device

listener

The listener instance of this context.

Type

Listener

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.

property default_resampler_index

The contexts 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).

destroy(self) → None

Destroy the context.

The context must not be current when this is called.

property doppler_factor

Factor to apply to all sources doppler calculations.

end_batch(self) → None

Continue processing the context and end batching.

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

Return if the channel configuration and sample type are supported by the context.

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(self) → None

Suspend the context to start batching.

update(self) → None

Update the context and all sources belonging to this context.

class palace.Buffer(Context context: Context, str name: str, existed: bool = False) → None

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
  • context (Context) The context from which the buffer is to be created and cached.

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

name

Audio file or resource name.

Type

str

Raises

RuntimeError If the buffer can neither be loaded nor be found when existed is set.

property channel_config

Buffers sample configuration.

destroy(self) → None

Free the buffers cache

This invalidates all other Buffer objects with the same name.

property frequency

Buffers frequency in hertz.

static from_decoder(Decoder decoder: Decoder, Context context: Context, str name: str) → Buffer

Return a buffer created by reading the given decoder.

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

  • context (Context) The context from which the buffer is to be created.

  • 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.

Raises

RuntimeError If the buffer cannot be created.

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(self, source: Optional[Source] = None) → 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

Buffers 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.

class palace.Source(Context context: Context) → None

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 sources destructioni upon completion of the block, even if an error occurs.

Parameters

context (Context) The context from which the source is to be created.

air_absorption_factor

Multiplier for the amount of atmospheric high-frequency absorption, 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.

property auxiliary_send

Connect the effect slot to the given send path.

Any filter properties on the send path remain as they were.

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(self) → None

Destroy the source, stop playback and release resources.

distance_range

Reference and maximum distance for current distance model.

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

Parameters
  • refdist (float) The distance at which the sources 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 effects 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(self, double 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.

Pending playback from a future buffer is not immediately canceled, but the fade timer starts with this call. If the future buffer then becomes ready, it will start mid-fade. Pending playback will be canceled if the fade out completes before the future buffer becomes ready.

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.

gain

Base linear volume gain, default to 1.0.

Raises

ValueError If set to a negative value.

gain_auto

Whether the direct paths 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 sources gain is clamped to after distance and cone attenuation are applied to the gain base, although before the filter gain adjustements.

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 on the Buffer or Decoder objects loop points.

offset

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

property offset_seconds

Source offset in seconds.

For streaming sources this will be the offset based on the decoders 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

Linear gain and gainhf multiplier when the listener is outside of the sources outer cone area.

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

  • gainhf (float) Linear gainhf 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(self) → None

Pause the source if it is playing.

property paused

Whether the source is currently paused.

property pending

Whether the source is waiting to play a future buffer.

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.

property playing_or_pending

Whether the source is currently playing or waiting to play in a future buffer.

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 sources position, velocity, and orientation are relative to the listener.

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(self) → 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.

spatialize

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, when playing a stereo buffer or stream. The angles go counter-clockwise, with 0 being in front and positive values going left.

This has no effect without the AL_EXT_STEREO_ANGLES extension.

stop(self) → None

Stop playback, releasing the buffer or decoder reference.

Any pending playback from a future buffer is canceled.

velocity

3D velocity in units per second.

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

class palace.SourceGroup(Context context: Context) → None

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 (Context) The context from which the source group is to be created.

destroy(self) → 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(self) → None

Pause all currently-playing sources that are under this group, including sub-groups.

pitch

Source group pitch.

This accumulates with its sources and sub-groups pitch.

resume_all(self) → None

Resume all paused sources that are under this group, including sub-groups.

property sources

Sources under this group.

stop_all(self) → None

Stop all sources that are under this group, including sub-groups.

property sub_groups

Source groups under this group.

class palace.AuxiliaryEffectSlot(Context context: Context) → None

An effect processor.

It takes the output mix of zero or more sources, applies DSP for the desired effect (as configured by a given Effect object), 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 (Context) The context to create the auxiliary effect slot.

Raises

RuntimeError If the effect slot cant be created.

destroy(self) → 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 effect

Effect to be held by the slot.

The given effect object may be altered or destroyed without affecting the effect slot.

property gain

Gain of the effect slot.

property send_auto

If set to True, the reverb effect will automatically apply adjustments to the sources send slot gains based on the effect properties.

Has no effect when using non-reverb effects. Default is True.

property source_sends

List of each Source object and its pairing send this effect slot is set on.

property use_count

Number of source sends the effect slot is used by. This is equivalent to calling len(tuple(self.source_sends)).

class palace.Effect(Context context: Context) → None

A collection of settings or parameters.

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

Parameters

context (Context) The context from which the effect is to be created.

property chorus_properties

The effect with the specified chorus properties.

It will be thrown if EAXReverb effect is not supported.

destroy(self) → None

Destroy the effect.

property reverb_properties

The effect with the specified reverb properties.

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

class palace.Decoder(Context context: Context, str name: str) → None

Generic audio decoder.

Parameters
  • context (Context) The context from which the decoder is to be created.

  • name (str) Audio file or resource name.

Raises

RuntimeError If decoder creation fails.

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 smart static method 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(self, Source source: Source, chunk_len: int, queue_size: int) → None

Stream audio asynchronously from the decoder.

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

Parameters
  • source (Source) The source object to play audio.

  • 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.

read(self, 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(self, pos: int) → bool

Seek to pos, specified in sample frames.

Return if the seek was successful.

static smart(Context context: Context, str name: str) → 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.

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.

read

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.

seek

Seek to pos, specified in sample frames.

Return if the seek was successful.

class palace.FileIO

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.

close

Close the file.

read

Read at most size bytes, returned as bytes.

seek

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).

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(self, str name: str, str channel_config: str, str sample_type: str, sample_rate: int, data: List[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 (List[int]) The audio data that is about to be fed to the OpenAL buffer.

device_disconnected(self, Device device: 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(self, str 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(self, Source source: 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 thats getting removed.

source_stopped(self, Source source: 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.

palace

Navigation

Contents:

Related Topics

©2019, 2020 Nguyễn Gia Phong et al. | Powered by Sphinx 2.4.3 & Alabaster 0.7.12 | Page source
</html>