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

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

classmethod __new__(*args, **kwargs)
loop

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

Type:

bool

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

classmethod __new__(*args, **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).

classmethod __new__(*args, **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.

    Added in version 1.2.

classmethod __new__(*args, **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:
  • 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

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

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

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.

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.

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.

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 orthogonal 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 orthogonal 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

have_ffmpeg()

Check if FFmpeg library is available.

Returns:

True if FFmpeg is found.

Return type:

bool

Added in version 1.4.

Exceptions

exception CannotSeekException
exception MediaException
exception MediaFormatException