SDL Audio tcod.sdl.audio¶
SDL audio playback and recording tools.
This module includes SDL’s low-level audio API and a naive implementation of an SDL mixer. If you have experience with audio mixing then you might be better off writing your own mixer or modifying the existing one which was written using Python/Numpy.
This module is designed to integrate with the wider Python ecosystem. It leaves the loading to sound samples to other libraries such as soundfile.
Example:
# Synchronous audio example
import time
import soundfile # pip install soundfile
import tcod.sdl.audio
device = tcod.sdl.get_default_playback().open() # Open the default output device
# AudioDevice's can be opened again to form a hierarchy
# This can be used to give music and sound effects their own configuration
device_music = device.open()
device_music.gain = 0 # Mute music
device_effects = device.open()
device_effects.gain = 10 ** (-6 / 10) # -6dB
sound, sample_rate = soundfile.read("example_sound.wav", dtype="float32") # Load an audio sample using SoundFile
stream = device_effects.new_stream(format=sound.dtype, frequency=sample_rate, channels=sound.shape[1])
stream.queue_audio(sound) # Play audio by appending it to the audio stream
stream.flush()
while stream.queued_samples: # Wait until stream is finished
time.sleep(0.001)
Added in version 13.5.
- class tcod.sdl.audio.AllowedChanges(value)[source]¶
Which parameters are allowed to be changed when the values given are not supported.
Deprecated since version 19.0: This is no longer used.
- ANY = 15¶
- CHANNELS = 4¶
- FORMAT = 2¶
- FREQUENCY = 1¶
- NONE = 0¶
- SAMPLES = 8¶
- class tcod.sdl.audio.AudioDevice(device_id: Any, /)[source]¶
An SDL audio device.
Example:
device = tcod.sdl.audio.get_default_playback().open() # Open a common audio device
Changed in version 16.0: Can now be used as a context which will close the device on exit.
Changed in version 19.0: Removed spec and callback attribute.
queued_samples, queue_audio, and dequeue_audio moved to
AudioStreamclass.- __enter__() Self[source]¶
Return self and enter a managed context.
Deprecated since version 19.0: Use
contextlib.closing()if you want to close this device after a context.
- __exit__(_type: builtins.type[BaseException] | None, _value: BaseException | None, _traceback: TracebackType | None, /) None[source]¶
Close the device when exiting the context.
- bind(streams: Iterable[AudioStream], /) None[source]¶
Bind one or more
AudioStream’s to this device.
- close() None[source]¶
Close this audio device. Using this object after it has been closed is invalid.
- convert(sound: ArrayLike, rate: int | None = None) NDArray[np.number][source]¶
Convert an audio sample into a format supported by this device.
Returns the converted array. This might be a reference to the input array if no conversion was needed.
- Parameters:
sound – An ArrayLike sound sample.
rate – The sample-rate of the input array. If None is given then it’s assumed to be the same as the device.
Added in version 13.6.
See also
- new_stream(format: DTypeLike, channels: int, frequency: int) AudioStream[source]¶
Create, bind, and return a new
AudioStreamfor this device.Added in version 19.0.
- open(format: DTypeLike | None = None, channels: int | None = None, frequency: int | None = None) Self[source]¶
Open a new logical audio device for this device.
Added in version 19.0.
- property gain: float¶
Get or set the logical audio device gain.
Default is 1.0 but can be set higher or zero.
Added in version 19.0.
- class tcod.sdl.audio.AudioStream(stream_p: Any, /)[source]¶
An SDL audio stream.
This class is commonly created with
AudioDevice.new_streamwhich creates a new stream bound to the device.Added in version 19.0.
- classmethod new(format: DTypeLike, channels: int, frequency: int, out_format: DTypeLike | None = None, out_channels: int | None = None, out_frequency: int | None = None) Self[source]¶
Create a new unbound AudioStream.
- static __new__(cls, stream_p: Any, /) AudioStream[source]¶
Return an AudioStream for the provided SDL_AudioStream* C pointer.
- flush() None[source]¶
Ensure all queued data is available.
This may queue silence to the end of the stream.
- queue_audio(samples: numpy.typing.ArrayLike) None[source]¶
Append audio samples to the audio data queue.
- property frequency_ratio: float¶
Get or set the frequency ratio, affecting the speed and pitch of the stream.
Higher values play the audio faster.
Default is 1.0.
- property gain: float¶
Get or set the audio stream gain.
Default is 1.0 but can be set higher or zero.
- property getter_callback: Callable[[AudioStream, AudioStreamCallbackData], Any] | None¶
Get or assign the stream get-callback for this stream.
- property putter_callback: Callable[[AudioStream, AudioStreamCallbackData], Any] | None¶
Get or assign the stream put-callback for this stream.
- class tcod.sdl.audio.AudioStreamCallbackData(additional_bytes: int, additional_samples: int, total_bytes: int, total_samples: int)[source]¶
Data provided to AudioStream callbacks.
Added in version 19.0.
- class tcod.sdl.audio.BasicMixer(**kwargs)[source]¶
An SDL sound mixer implemented in Python and Numpy.
Example:
import time import soundfile # pip install soundfile import tcod.sdl.audio device = tcod.sdl.audio.get_default_playback().open() mixer = tcod.sdl.audio.BasicMixer(device) # Setup BasicMixer with the default audio output sound, sample_rate = soundfile.read("example_sound.wav") # Load an audio sample using SoundFile sound = mixer.device.convert(sound, sample_rate) # Convert this sample to the format expected by the device channel = mixer.play(sound) # Start asynchronous playback, audio is mixed on a separate Python thread while channel.busy: # Wait until the sample is done playing time.sleep(0.001)
Added in version 13.6.
Changed in version 19.0: Added frequency and channels parameters.
Deprecated since version 19.0: Changes in the SDL3 API have made this classes usefulness questionable. This class should be replaced with custom streams.
- get_channel(key: Hashable) Channel[source]¶
Return a channel tied to with the given key.
Channels are initialized as you access them with this function.
intchannels starting from zero are used internally.This can be used to generate a
"music"channel for example.
- play(sound: ArrayLike, *, volume: float | tuple[float, ...] = 1.0, loops: int = 0, on_end: Callable[[Channel], None] | None = None) Channel[source]¶
Play a sound, return the channel the sound is playing on.
- Parameters:
sound – The sound to play. This a Numpy array matching the format of the loaded audio device.
volume – The volume to play the sound at. You can also pass a tuple of floats to set the volume for each channel/speaker.
loops – How many times to play the sound, -1 can be used to loop the sound forever.
on_end – A function to call when this sound has ended. This is called with the
Channelwhich was playing the sound.
- device¶
The
AudioDevice
- class tcod.sdl.audio.Channel[source]¶
An audio channel for
BasicMixer. UseBasicMixer.get_channelto initialize this object.Added in version 13.6.
- play(sound: ArrayLike, *, volume: float | tuple[float, ...] = 1.0, loops: int = 0, on_end: Callable[[Channel], None] | None = None) None[source]¶
Play an audio sample, stopping any audio currently playing on this channel.
Parameters are the same as
BasicMixer.play.
- mixer: BasicMixer¶
The
BasicMixeris channel belongs to.
- tcod.sdl.audio.convert_audio(in_sound: ArrayLike, in_rate: int, *, out_rate: int, out_format: DTypeLike, out_channels: int) NDArray[np.number][source]¶
Convert an audio sample into a format supported by this device.
Returns the converted array in the shape (sample, channel). This will reference the input array data if no conversion was needed.
- Parameters:
in_sound – The input ArrayLike sound sample. Input format and channels are derived from the array.
in_rate – The sample-rate of the input array.
out_rate – The sample-rate of the output array.
out_format – The output format of the converted array.
out_channels – The number of audio channels of the output array.
Examples:
>>> tcod.sdl.audio.convert_audio(np.zeros(5), 44100, out_rate=44100, out_format=np.uint8, out_channels=1).T array([[128, 128, 128, 128, 128]], dtype=uint8) >>> tcod.sdl.audio.convert_audio(np.zeros(3), 22050, out_rate=44100, out_format=np.int8, out_channels=2).T array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]], dtype=int8)
Added in version 13.6.
Changed in version 16.0: Now converts floating types to np.float32 when SDL doesn’t support the specific format.
See also
- tcod.sdl.audio.get_capture_devices() dict[str, AudioDevice][source]¶
Iterate over the available audio capture devices.
Changed in version 19.0: Now returns a dictionary of
AudioDevice.
- tcod.sdl.audio.get_default_playback() AudioDevice[source]¶
Return the default playback device.
Example:
playback_device = tcod.sdl.audio.get_default_playback().open()
Added in version 19.0.
- tcod.sdl.audio.get_default_recording() AudioDevice[source]¶
Return the default recording device.
Example:
recording_device = tcod.sdl.audio.get_default_recording().open()
Added in version 19.0.
- tcod.sdl.audio.get_devices() dict[str, AudioDevice][source]¶
Iterate over the available audio output devices.
Changed in version 19.0: Now returns a dictionary of
AudioDevice.
- tcod.sdl.audio.open(name: str | None = None, capture: bool = False, *, frequency: int = 44100, format: DTypeLike = <class 'numpy.float32'>, channels: int = 2, samples: int = 0, allowed_changes: AllowedChanges = <AllowedChanges.NONE: 0>, paused: bool = False, callback: None | Literal[True] | Callable[[AudioDevice, NDArray[Any]], None] = None) AudioDevice[source]¶
Open an audio device for playback or capture and return it.
- Parameters:
name – The name of the device to open, or None for the most reasonable default.
capture – True if this is a recording device, or False if this is an output device.
frequency – The desired sample rate to open the device with.
format – The data format to use for samples as a NumPy dtype.
channels – The number of speakers for the device. 1, 2, 4, or 6 are typical options.
samples – This parameter is ignored.
allowed_changes – This parameter is ignored.
paused – If True then the device will begin in a paused state. It can then be unpaused by assigning False to
AudioDevice.paused.callback – An optional callback to use, this is deprecated.
If a callback is given then it will be called with the AudioDevice and a Numpy buffer of the data stream. This callback will be run on a separate thread.
Changed in version 19.0: SDL3 returns audio devices differently, exact formatting is set with
AudioDevice.new_streaminstead.samples and allowed_changes are ignored.
Deprecated since version 19.0: This is an outdated method. Use
AudioDevice.openinstead, for example:tcod.sdl.audio.get_default_playback().open()