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:

None

pause() None

Pause playback of the current source.

This has no effect if the player is already paused.

Return type:

None

queue(
source: Source | Iterable[Source],
) 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:

None

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:

None

seek_next_frame() None

Step forwards one video frame in the current source.

Return type:

None

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:

None

delete() None

Release the resources acquired by this player.

The internal audio player and the texture will be deleted.

Return type:

None

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.

Parameters:

dt (float | None) – The time elapsed since the last call to update_texture.

Return type:

None

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 to False. If loop attribute is set to True, the current source will start to play again until next_source() is called or loop is set to False.

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 and cone_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 is False, 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, or None.

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

__init__() None

Initialize the Player with a MasterClock.

__new__(**kwargs)
loop

Loop the current source indefinitely or until next_source() is called. Defaults to False.

Type:

bool

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.

play() None

Begin playing all players in the group simultaneously.

Return type:

None

pause() None

Pause all players in the group simultaneously.

Return type:

None

__init__(players: Iterable[Player]) None

Initialize the PlayerGroup with the players.

__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:
  • channels (int) – The number of channels: 1 for mono or 2 for stereo (pyglet does not yet support surround-sound sources).

  • sample_size (int) – Bits per sample; only 8 or 16 are supported.

  • sample_rate (int) – Samples per second (in Hertz).

__init__(channels: int, sample_size: int, sample_rate: int) None
__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:
  • width (int) – Width of video image, in pixels.

  • height (int) – Height of video image, in pixels.

  • sample_aspect (float) – Aspect ratio (width over height) of a single video pixel.

  • frame_rate (float) –

    Frame rate (frames per second) of the video.

    New in version 1.2.

__init__(width: int, height: int, sample_aspect: float = 1.0) None
__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.

__init__(
data: bytes | Array,
length: int,
timestamp: float = 0.0,
duration: float = 0.0,
events: List[MediaEvent] | None = None,
) None
class SourceInfo

Source metadata information.

Fields are the empty string or zero if the information is not available.

Parameters:
  • title (str) – Title

  • author (str) – Author

  • copyright (str) – Copyright statement

  • comment (str) – Comment

  • album (str) – Album name

  • year (int) – Year

  • track (int) – Track number

  • genre (str) – Genre

New in version 1.2.

class Source

An audio and/or video source.

Parameters:
  • audio_format (AudioFormat) – Format of the audio in this source, or None if the source is silent.

  • video_format (VideoFormat) – Format of the video in this source, or None 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:

Animation

Returns:

pyglet.image.Animation

get_audio_data(
num_bytes: int,
compensation_time=0.0,
) AudioData | None

Get next packet of audio data.

Parameters:
  • num_bytes (int) – A size hint for the amount of bytes to return, but the returned amount may be lower or higher.

  • compensation_time (float) – Time in sec to compensate due to a difference between the master clock and the audio clock.

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:

AudioData

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:

pyglet.image.AbstractImage

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:

float

get_queue_source() Source

Return the Source to be used as the queue source for a player.

Default implementation returns self.

Return type:

Source

Returns:

Source

is_precise() bool

bool: Whether this source is considered precise.

x bytes on source s are considered aligned if x % 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 where r < x and r is aligned.

A source is not precise if it does any of these:

  • Return less than x bytes for an aligned request of x bytes although data still remains so that an additional request would return additional AudioData / not None.

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

Return type:

Player

Returns:

Player

save(
filename: str,
file: BinaryIO | None = None,
encoder: MediaEncoder | None = None,
) 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:

None

seek(timestamp: float) None

Seek to given timestamp.

Parameters:

timestamp (float) – Time where to seek in the source. The timestamp will be clamped to the duration of the source.

Return type:

None

property duration: float

The length of the source, in seconds.

Not all source durations can be determined; in this case the value is None.

Read-only.

Type:

float

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.

delete() None

Release the resources held by this StreamingSource.

Return type:

None

get_queue_source() StreamingSource

Return the Source to be used as the source for a player.

Default implementation returns self.

Return type:

StreamingSource

Returns:

Source

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 in source.

Parameters:

source (Source) – The source to read and decode audio and video data from.

__init__(source: Source) None
get_audio_data(
num_bytes: float,
compensation_time: float = 0.0,
) AudioData | None

The StaticSource does not provide audio data.

When the StaticSource is queued on a Player, it creates a StaticMemorySource containing its internal audio data and audio format.

Raises:

RuntimeError

Return type:

AudioData | None

get_queue_source() StaticMemorySource | None

Return the Source to be used as the queue source for a player.

Default implementation returns self.

Return type:

StaticMemorySource | None

Returns:

Source

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,
) None

Construct a memory source over the given data buffer.

get_audio_data(
num_bytes: float,
compensation_time: float = 0.0,
) AudioData | None

Get next packet of audio data.

Parameters:

num_bytes (int) – Maximum number of bytes of data to return.

Returns:

Next packet of audio data, or None if there is no (more) data.

Return type:

AudioData

is_precise() bool

bool: Whether this source is considered precise.

x bytes on source s are considered aligned if x % 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 where r < x and r is aligned.

A source is not precise if it does any of these:

  • Return less than x bytes for an aligned request of x bytes although data still remains so that an additional request would return additional AudioData / not None.

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

seek(timestamp: float) None

Seek to given timestamp.

Parameters:

timestamp (float) – Time where to seek in the source.

Return type:

None

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

property up_orientation

A vector giving the “up” orientation of the listener.

The orientation is given as a tuple of floats (x, y, z), and has no unit. The up orientation should be orthagonal to the forward orientation.

Type:

3-tuple of float

property volume

The master volume for sound playback.

All sound volumes are multiplied by this master volume before being played. A value of 0 will silence playback (but still consume resources). The nominal volume is 1.0.

Type:

float

class MediaEvent

Representation of a media event.

These events are used internally by some audio driver implementation to communicate events to the Player. One example is the on_eos event.

Parameters:
  • event (str) – Event description.

  • timestamp (float) – The time when this event happens.

  • *args – Any required positional argument to go along with this event.

__init__(event, timestamp=0.0, *args)

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,
) Source | StreamingSource

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 if file is unspecified.

  • file (BinaryIO | None) – An optional file-like object containing the source data.

  • streaming (bool) – If False, a StaticSource will be returned; otherwise (default) a StreamingSource 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:

Source | StreamingSource

have_ffmpeg()

Check if FFmpeg library is available.

Returns:

True if FFmpeg is found.

Return type:

bool

New in version 1.4.

Exceptions

exception CannotSeekException
exception MediaException
exception MediaFormatException