pyglet.media

Submodules

Details

Audio and video playback.

pyglet can play WAV files, and if AVbin 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 (currently, only OpenAL is supported):

player = Player()

A Source is used to decode arbitrary audio and video files. It is associated with a single player by “queuing” 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. Also an explicit call to gc.collect() can be used to collect unused resources.

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 be paused immediately on this source.

Parameters:source (pyglet.media.Source) – The source to queue.
seek(time)

Seek for playback to the indicated timestamp in seconds on the current source. If the timestamp is outside the duration of the source, it will be clamped to the end.

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

Move immediately to the next queued source.

There may be a gap in playback while the audio buffer is refilled.

delete()

Tear down the player and any child objects.

update_texture(dt=None, time=None)

Manually update the texture from the current source. This happens automatically, so you shouldn’t need to call this method.

next()

Warning

Deprecated. Use next_source instead.

Events

on_eos()
on_player_eos()

The player ran out of sources.

on_source_group_eos()

The current source group ran out of data.

The default behaviour is to advance to the next source group if possible.

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

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 sound. The playback time returned represents the time encoded in the source, and may not reflect actual time passed due to pitch shifting or pausing.

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

class PlayerGroup(players)

Group of players that can be played and paused simultaneously.

Variables:players (list of Player) – Players 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.

Variables:
  • 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 track. 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.

Variables:
  • 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. AVbin 8 or later is required, otherwise the frame rate will be None. .. versionadded:: 1.2.
class AudioData(data, length, timestamp, duration, events)

A single packet of audio data.

This class is used internally by pyglet.

Variables:
  • 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 of MediaEvent) – List of events contained within this packet. Events are timestamped relative to this audio packet.
class SourceInfo

Source metadata information.

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

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

Variables:
  • 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. .. versionadded:: 1.2
get_animation()

Import all video frames into memory as an Animation.

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.

This method is unsuitable for videos running longer than a few seconds.

New in version 1.1.

Return type:pyglet.image.Animation
get_audio_data(bytes)

Get next packet of audio data.

Parameters:bytes (int) – Maximum number of bytes of data to return.
Return type:AudioData
Returns:Next packet of audio data, or None if there is no (more) data.
get_next_video_frame()

Get the next video frame.

Video frames may share memory: the previous frame may be invalidated or corrupted when this method is called unless the application has made a copy of it.

New in version 1.1.

Return type:pyglet.image.AbstractImage
Returns:The next video frame image, or None if the video frame could not be decoded or there are no more video frames.
get_next_video_timestamp()

Get the timestamp of the next video frame.

New in version 1.1.

Return type:float
Returns:The next timestamp, or None if there are no more video frames.
play()

Play the source.

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

Return type:Player
seek(timestamp)

Seek to given timestamp.

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.sources.base.Source

A source that is decoded as it is being played, and can only be queued once.

delete()
is_queued

Determine if this source has been queued on a Player yet.

Read-only.

Type:bool
class StaticSource(source)

Bases: pyglet.media.sources.base.Source

A source that has been completely decoded in memory. This source can be queued onto multiple players any number of times.

get_audio_data(bytes)
class SourceGroup(audio_format, video_format)

Read data from a queue of sources, with support for looping. All sources must share the same audio format.

Variables:audio_format (AudioFormat) – Required audio format for queued sources.
get_audio_data(bytes)

Get next audio packet.

Parameters:bytes (int) – Hint for preferred size of audio packet; may be ignored.
Return type:AudioData
Returns:Audio data, or None if there is no more data.
get_current_source()
get_next_video_frame()

Get the next video frame.

Video frames may share memory: the previous frame may be invalidated or corrupted when this method is called unless the application has made a copy of it.

Return type:pyglet.image.AbstractImage
Returns:The next video frame image, or None if the video frame could not be decoded or there are no more video frames.
get_next_video_timestamp()

Get the timestamp of the next video frame.

Return type:float
Returns:The next timestamp, or None if there are no more video frames.
has_next()
next(immediate=True)

Warning

Deprecated. Use next_source instead.

next_source(immediate=True)
queue(source)
seek(time)
translate_timestamp(timestamp)

Get source-relative timestamp for the audio player’s timestamp.

loop

Loop the current source indefinitely or until next is called. Initially False.

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

Functions

get_audio_driver()
load(filename, file=None, streaming=True)

Load a source from a file.

Currently the file argument is not supported; media files must exist as real paths.

Parameters:
  • filename (str) – Filename of the media file to load.
  • file (file-like object) – Not yet supported.
  • streaming (bool) – If False, a StaticSource will be returned; otherwise (default) a StreamingSource is created.
Return type:

Source

Exceptions

exception CannotSeekException
exception MediaException
exception MediaFormatException

Table Of Contents

Previous topic

pyglet.input

Next topic

pyglet.media.procedural