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

Begin playing the current source.

This has no effect if the player is already playing.

pause()

Pause playback of the current source.

This has no effect if the player is already paused.

queue(source)

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.

Parameters:source (Source or Iterable[Source]) – The source to queue.
seek(time)

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.

Parameters:time (float) – The time where to seek in the source, clamped to the beginning and end of the source.
seek_next_frame()

Step forwards one video frame in the current source.

get_texture()

Get the texture for the current video frame.

You should call this method every time you display a frame of video, as multiple textures might be used. The return value will be None if there is no video in the current source.

Returns:pyglet.image.Texture

Deprecated since version 1.4: Use texture instead

next_source()

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.

delete()

Release the resources acquired by this player.

The internal audio player and the texture will be deleted.

update_texture(dt=None)

Manually update the texture from the current source.

This happens automatically, so you shouldn’t need to call this method.

Parameters:dt (float) – The time elapsed since the last call to update_texture.

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

Read-only. Determine if the player state is playing.

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.

Type:bool
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.

Type:Source
texture

Get the texture for the current video frame.

You should call this method every time you display a frame of video, as multiple textures might be used. The return value will be None if there is no video in the current source.

Type:pyglet.image.Texture
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.

Type:float
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).

loop

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

Type:bool

New in version 1.4.

class PlayerGroup(players)

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.

Parameters:players (List[Player]) – List of Player s in this group.
play()

Begin playing all players in the group simultaneously.

pause()

Pause all players in the group simultaneously.

class AudioFormat(channels, sample_size, sample_rate)

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).
class VideoFormat(width, height, sample_aspect=1.0)

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.

class AudioData(data, length, timestamp, duration, events)

A single packet of audio data.

This class is used internally by pyglet.

Parameters:
  • data (str or ctypes array or pointer) – 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.events.MediaEvent]) – List of events contained within this packet. Events are timestamped relative to this audio packet.
consume(num_bytes, audio_format)

Remove some data from the beginning of the packet.

All events are cleared.

Parameters:
  • num_bytes (int) – The number of bytes to consume from the packet.
  • audio_format (AudioFormat) – The packet audio format.
get_string_data()

Return data as a bytestring.

Returns:Data as a (byte)string. For Python 3 it’s a bytestring while for Python 2 it’s a string.
Return type:bytes or str
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.

is_player_source

Determine if this source is a player current source.

Check on a Player if this source is the current source.

Type:bool
get_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.

Returns:pyglet.image.Animation
get_audio_data(bytes, compensation_time=0.0)

Get next packet of audio data.

Parameters:
  • bytes (int) – Maximum number of bytes of data to return.
  • compensation_time (float) – Time in sec to compensate due to a difference between the master clock and the audio clock.
Returns:

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

Return type:

AudioData

get_next_video_frame()

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

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

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

Default implementation returns self.

play()

Play the source.

This is a convenience method which creates a Player for this source and plays it immediately.

Returns:Player
seek(timestamp)

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

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: pyglet.media.codecs.base.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()

Release the resources held by this StreamingSource.

get_queue_source()

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

Default implementation returns self.

Returns:Source
is_queued

Determine if this source is a player current source.

Check on a Player if this source is the current source.

Warning

Deprecated. Use is_player_source instead.

Type:bool
class StaticSource(source)

Bases: pyglet.media.codecs.base.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.
get_audio_data(bytes, compensation_time=0.0)

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
get_queue_source()

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

Default implementation returns self.

class StaticMemorySource(data, audio_format)

Bases: pyglet.media.codecs.base.StaticSource

Helper class for default implementation of StaticSource.

Do not use directly. This class is used internally by pyglet.

Parameters:
get_audio_data(bytes, compensation_time=0.0)

Get next packet of audio data.

Parameters:
  • bytes (int) – Maximum number of bytes of data to return.
  • compensation_time (float) – Not used in this class.
Returns:

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

Return type:

AudioData

seek(timestamp)

Seek to given timestamp.

Parameters:timestamp (float) – Time where to seek in the source.
class AbstractListener

The listener properties for positional audio.

You can obtain the singleton instance of this class by calling AbstractAudioDriver.get_listener().

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
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
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
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(timestamp, event, *args)

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:
  • timestamp (float) – The time where this event happens.
  • event (str) – Event description.
  • *args – Any required positional argument to go along with this event.

Functions

get_audio_driver()

Get the preferred audio driver for the current platform.

Currently pyglet supports DirectSound, PulseAudio and OpenAL drivers. If the platform supports more than one of those audio drivers, the application can give its preference with pyglet.options audio keyword. See the Programming guide, section Sound and video.

Returns:The concrete implementation of the preferred audio driver for this platform.
Return type:AbstractAudioDriver
load(filename, file=None, streaming=True, decoder=None)

Load a Source from a 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 to use.

Parameters:
  • filename (str) – Used to guess the media format, and to load the file if file is unspecified.
  • file (file-like object or None) – Source of media data in any supported format.
  • streaming (bool) – If False, a StaticSource will be returned; otherwise (default) a StreamingSource is created.
  • decoder (MediaDecoder or None) – A specific decoder you wish to use, rather than relying on automatic detection. If specified, no other decoders are tried.
Return type:

StreamingSource or Source

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 MediaDecodeException
exception_priority = 10
exception MediaEncodeException
exception MediaException
exception MediaFormatException