pyglet.media
Submodules
Details
Audio and video playback.
pyglet can play WAV files, and if FFmpeg is installed, many other audio and video formats.
Playback is handled by the Player
class, which reads raw data from
Source
objects and provides methods for pausing, seeking, adjusting
the volume, and so on. The Player
class implements the best
available audio device.
player = Player()
A Source
is used to decode arbitrary audio and video files. It is
associated with a single player by “queueing” it:
source = load('background_music.mp3')
player.queue(source)
Use the Player
to control playback.
If the source contains video, the Source.video_format()
attribute
will be non-None, and the Player.texture
attribute will contain the
current video image synchronised to the audio.
Decoding sounds can be processor-intensive and may introduce latency,
particularly for short sounds that must be played quickly, such as bullets or
explosions. You can force such sounds to be decoded and retained in memory
rather than streamed from disk by wrapping the source in a
StaticSource
:
bullet_sound = StaticSource(load('bullet.wav'))
The other advantage of a StaticSource
is that it can be queued on
any number of players, and so played many times simultaneously.
Pyglet relies on Python’s garbage collector to release resources when a player has finished playing a source. In this way some operations that could affect the application performance can be delayed.
The player provides a Player.delete()
method that can be used to
release resources immediately.
Classes
- class Player
High-level sound and video player.
Methods
- play() None
Begin playing the current source.
This has no effect if the player is already playing.
- Return type:
- pause() None
Pause playback of the current source.
This has no effect if the player is already paused.
- Return type:
- queue( ) None
Queue the source on this player.
If the player has no source, the player will start to play immediately or pause depending on its
playing
attribute.- Return type:
- seek(timestamp: float) None
Seek for playback to the indicated timestamp on the current source.
Timestamp is expressed in seconds. If the timestamp is outside the duration of the source, it will be clamped to the end.
- Return type:
- next_source() None
Move immediately to the next source in the current playlist.
If the playlist is empty, discard it and check if another playlist is queued. There may be a gap in playback while the audio buffer is refilled.
- Return type:
- delete() None
Release the resources acquired by this player.
The internal audio player and the texture will be deleted.
- Return type:
- update_texture(dt: float | None = None) None
Manually update the texture from the current source.
This happens automatically, so you shouldn’t need to call this method.
Events
- on_eos()
The current source ran out of data.
The default behaviour is to advance to the next source in the playlist if the
loop
attribute is set toFalse
. Ifloop
attribute is set toTrue
, the current source will start to play again untilnext_source()
is called orloop
is set toFalse
.
- on_player_eos()
The player ran out of sources. The playlist is empty.
- on_player_next_source()
The player starts to play the next queued source in the playlist.
This is a useful event for adjusting the window size to the new source
VideoFormat
for example.
Attributes
- cone_inner_angle
The interior angle of the inner cone.
The angle is given in degrees, and defaults to 360. When the listener is positioned within the volume defined by the inner cone, the sound is played at normal gain (see
volume
).
- cone_outer_angle
The interior angle of the outer cone.
The angle is given in degrees, and defaults to 360. When the listener is positioned within the volume defined by the outer cone, but outside the volume defined by the inner cone, the gain applied is a smooth interpolation between
volume
andcone_outer_gain
.
- cone_orientation
The direction of the sound in 3D space.
The direction is specified as a tuple of floats (x, y, z), and has no unit. The default direction is (0, 0, -1). Directional effects are only noticeable if the other cone properties are changed from their default values.
- cone_outer_gain
The gain applied outside the cone.
When the listener is positioned outside the volume defined by the outer cone, this gain is applied instead of
volume
.
- min_distance
The distance beyond which the sound volume drops by half, and within which no attenuation is applied.
The minimum distance controls how quickly a sound is attenuated as it moves away from the listener. The gain is clamped at the nominal value within the min distance. By default the value is 1.0.
The unit defaults to meters, but can be modified with the listener properties.
- max_distance
The distance at which no further attenuation is applied.
When the distance from the listener to the player is greater than this value, attenuation is calculated as if the distance were value. By default the maximum distance is infinity.
The unit defaults to meters, but can be modified with the listener properties.
- pitch
The pitch shift to apply to the sound.
The nominal pitch is 1.0. A pitch of 2.0 will sound one octave higher, and play twice as fast. A pitch of 0.5 will sound one octave lower, and play twice as slow. A pitch of 0.0 is not permitted.
- playing
The current playing state.
The playing property is irrespective of whether or not there is actually a source to play. If playing is
True
and a source is queued, it will begin to play immediately. If playing isFalse
, it is implied that the player is paused. There is no other possible state.
- position
The position of the sound in 3D space.
The position is given as a tuple of floats (x, y, z). The unit defaults to meters, but can be modified with the listener properties.
- source
Read-only. The current
Source
, orNone
.
- texture
Get the texture for the current video frame, if any.
You should query this property every time you display a frame of video, as multiple textures might be used. This property will be
None
if the current Source does not contain video.
- time
Read-only. Current playback time of the current source.
The playback time is a float expressed in seconds, with 0.0 being the beginning of the media. The playback time returned represents the player master clock time which is used to synchronize both the audio and the video.
- volume
The volume level of sound playback.
The nominal level is 1.0, and 0.0 is silence.
The volume level is affected by the distance from the listener (if positioned).
- __new__(**kwargs)
- loop
Loop the current source indefinitely or until
next_source()
is called. Defaults toFalse
.- Type:
New in version 1.4.
- class PlayerGroup
Group of players that can be played and paused simultaneously.
Create a player group for the given list of players.
All players in the group must currently not belong to any other group.
- __new__(**kwargs)
- class AudioFormat
Audio details.
An instance of this class is provided by sources with audio tracks. You should not modify the fields, as they are used internally to describe the format of data provided by the source.
- Parameters:
- __new__(**kwargs)
- class VideoFormat
Video details.
An instance of this class is provided by sources with a video stream. You should not modify the fields.
Note that the sample aspect has no relation to the aspect ratio of the video image. For example, a video image of 640x480 with sample aspect 2.0 should be displayed at 1280x480. It is the responsibility of the application to perform this scaling.
- Parameters:
- __new__(**kwargs)
- class AudioData
A single packet of audio data.
This class is used internally by pyglet.
- Parameters:
data (bytes, ctypes array, or supporting buffer protocol) – Sample data.
length (int) – Size of sample data, in bytes.
timestamp (float) – Time of the first sample, in seconds.
duration (float) – Total data duration, in seconds.
events (List[
pyglet.media.drivers.base.MediaEvent
]) – List of events contained within this packet. Events are timestamped relative to this audio packet.
Deprecated since version 2.0.10: timestamp and duration are unused and will be removed eventually.
- class SourceInfo
Source metadata information.
Fields are the empty string or zero if the information is not available.
- Parameters:
New in version 1.2.
- class Source
An audio and/or video source.
- Parameters:
audio_format (
AudioFormat
) – Format of the audio in this source, orNone
if the source is silent.video_format (
VideoFormat
) – Format of the video in this source, orNone
if there is no video.info (
SourceInfo
) –Source metadata such as title, artist, etc; or
None
if the` information is not available.New in version 1.2.
- Class Variables:
is_player_source (bool) – Determine if this source is a player current source.
Check on a
Player
if this source is the current source.
- get_animation() Animation
Import all video frames into memory.
An empty animation will be returned if the source has no video. Otherwise, the animation will contain all unplayed video frames (the entire source, if it has not been queued on a player). After creating the animation, the source will be at EOS (end of stream).
This method is unsuitable for videos running longer than a few seconds.
New in version 1.1.
- Return type:
- Returns:
pyglet.image.Animation
- get_audio_data(
- num_bytes: int,
- compensation_time=0.0,
Get next packet of audio data.
- Parameters:
Deprecated since version 2.0.10: compensation_time: Will always be given as
0.0
.- Returns:
Next packet of audio data, or
None
if there is no (more) data.- Return type:
- get_next_video_frame() AbstractImage | None
Get the next video frame.
New in version 1.1.
- Returns:
The next video frame image, or
None
if the video frame could not be decoded or there are no more video frames.- Return type:
- get_next_video_timestamp() float | None
Get the timestamp of the next video frame.
New in version 1.1.
- Returns:
The next timestamp, or
None
if there are no more video frames.- Return type:
- get_queue_source() Source
Return the
Source
to be used as the queue source for a player.Default implementation returns
self
.
- is_precise() bool
bool: Whether this source is considered precise.
x
bytes on sources
are considered aligned ifx % s.audio_format.bytes_per_frame == 0
, so there’d be no partial audio frame in the returned data.A source is precise if - for an aligned request of
x
bytes - it returns::rtype:bool
If
x
or more bytes are available,x
bytes.If not enough bytes are available anymore,
r
bytes wherer < x
andr
is aligned.
A source is not precise if it does any of these:
Return less than
x
bytes for an aligned request ofx
bytes although data still remains so that an additional request would return additionalAudioData
/ notNone
.Return more bytes than requested.
Return an unaligned amount of bytes for an aligned request.
pyglet’s internals are guaranteed to never make unaligned requests, or requests of less than 1024 bytes.
If this method returns
False
, pyglet will wrap the source in an alignment-forcing buffer creating additional overhead.If this method is overridden to return
True
although the source does not comply with the requirements above, audio playback may be negatively impacted at best and memory access violations occur at worst.- Returns:
bool: Whether the source is precise.
- play() Player
Play the source.
This is a convenience method which creates a Player for this source and plays it immediately.
- save( ) None
Save this Source to a file.
- Parameters:
- filenamestr
Used to set the file format, and to open the output file if file is unspecified.
- filefile-like object or None
File to write audio data to.
- encoderMediaEncoder or None
If unspecified, all encoders matching the filename extension are tried. If all fail, the exception from the first one attempted is raised.
- Return type:
- class StreamingSource
Bases:
Source
A source that is decoded as it is being played.
The source can only be played once at a time on any
Player
.- get_queue_source() StreamingSource
Return the
Source
to be used as the source for a player.Default implementation returns self.
- Return type:
- Returns:
- class StaticSource
Bases:
Source
A source that has been completely decoded in memory.
This source can be queued onto multiple players any number of times.
Construct a
StaticSource
for the data insource
.- Parameters:
source (Source) – The source to read and decode audio and video data from.
- get_audio_data( ) AudioData | None
The StaticSource does not provide audio data.
When the StaticSource is queued on a
Player
, it creates aStaticMemorySource
containing its internal audio data and audio format.- Raises:
- Return type:
- get_queue_source() StaticMemorySource | None
Return the
Source
to be used as the queue source for a player.Default implementation returns
self
.- Return type:
- Returns:
- class StaticMemorySource
Bases:
StaticSource
Helper class for default implementation of
StaticSource
.Do not use directly. This class is used internally by pyglet.
- Parameters:
data (readable buffer) – The audio data.
audio_format (AudioFormat) – The audio format.
- __init__(
- data,
- audio_format: AudioFormat,
Construct a memory source over the given data buffer.
- is_precise() bool
bool: Whether this source is considered precise.
x
bytes on sources
are considered aligned ifx % s.audio_format.bytes_per_frame == 0
, so there’d be no partial audio frame in the returned data.A source is precise if - for an aligned request of
x
bytes - it returns::rtype:bool
If
x
or more bytes are available,x
bytes.If not enough bytes are available anymore,
r
bytes wherer < x
andr
is aligned.
A source is not precise if it does any of these:
Return less than
x
bytes for an aligned request ofx
bytes although data still remains so that an additional request would return additionalAudioData
/ notNone
.Return more bytes than requested.
Return an unaligned amount of bytes for an aligned request.
pyglet’s internals are guaranteed to never make unaligned requests, or requests of less than 1024 bytes.
If this method returns
False
, pyglet will wrap the source in an alignment-forcing buffer creating additional overhead.If this method is overridden to return
True
although the source does not comply with the requirements above, audio playback may be negatively impacted at best and memory access violations occur at worst.- Returns:
bool: Whether the source is precise.
- class AbstractListener
The listener properties for positional audio.
You can obtain the singleton instance of this class by calling
AbstractAudioDriver.get_listener()
.- property forward_orientation
A vector giving the direction the listener is facing.
The orientation is given as a tuple of floats (x, y, z), and has no unit. The forward orientation should be orthagonal to the up orientation.
- Type:
3-tuple of float
- property position
The position of the listener in 3D space.
The position is given as a tuple of floats (x, y, z). The unit defaults to meters, but can be modified with the listener properties.
- Type:
3-tuple of float
Functions
- get_audio_driver()
Get the preferred audio driver for the current platform.
See
pyglet.options
audio
, and the Programming guide, section Playing Sound and Video for more information on setting the preferred driver.- Returns:
- The concrete implementation of the preferred
audio driver for this platform.
- Return type:
AbstractAudioDriver
- load(
- filename: str,
- file: BinaryIO | None = None,
- streaming: bool = True,
- decoder: MediaDecoder | None = None,
Load a Source from disk, or an opened file.
All decoders that are registered for the filename extension are tried. If none succeed, the exception from the first decoder is raised. You can also specifically pass a decoder instance to use.
- Parameters:
filename (
str
) – Used to guess the media format, and to load the file iffile
is unspecified.file (
BinaryIO
|None
) – An optional file-like object containing the source data.streaming (
bool
) – IfFalse
, aStaticSource
will be returned; otherwise (default) aStreamingSource
is created.decoder (
MediaDecoder
|None
) – A specific decoder you wish to use, rather than relying on automatic detection. If specified, no other decoders are tried.
- Return type:
Exceptions
- exception CannotSeekException
- exception MediaException
- exception MediaFormatException