This module contains functions for dealing with the keyboard.
The pygame.event queue gets pygame.KEYDOWN and pygame.KEYUP events when the keyboard buttons are pressed and released. Both events have key and mod attributes.
The pygame.KEYDOWN event has the additional attributes unicode and scancode.
New in pygame 2.0.0: The pygame.TEXTINPUT event is preferred to the unicode attribute of pygame.KEYDOWN. The attribute text contains the input.
The following is a list of all the constants (from pygame.locals) used to represent keyboard keys.
Portability note: The integers for key constants differ between pygame 1 and 2. Always use key constants (K_a) rather than integers directly (97) so that your key handling code works well on both pygame 1 and pygame 2.
The keyboard also has a list of modifier states (from pygame.locals) that can be assembled by bitwise-ORing them together.
The modifier information is contained in the mod attribute of the pygame.KEYDOWN and pygame.KEYUP events. The mod attribute is a bitmask of all the modifier keys that were in a pressed state when the event occurred. The modifier information can be decoded using a bitwise AND (except for KMOD_NONE, which should be compared using equals ==). For example:
Returns True when the display window has keyboard focus from the system. If the display needs to ensure it does not lose keyboard focus, it can use pygame.event.set_grab() to grab all input.
Returns a sequence of boolean values representing the state of every key on the keyboard. Use the key constant values to index the array. A True value means the that button is pressed.
Note
Getting the list of pushed buttons with this function is not the proper way to handle text entry from the user. There is no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to pygame.key.get_pressed(). There is also no way to translate these pushed keys into a fully translated character value. See the pygame.KEYDOWN events on the pygame.event queue for this functionality.
Returns a single integer representing a bitmask of all the modifier keys being held. Using bitwise operators you can test if specific modifier keys are pressed.
Create a bitmask of the modifier key constants you want to impose on your program.
When the keyboard repeat is enabled, keys that are held down will generate multiple pygame.KEYDOWN events. The delay parameter is the number of milliseconds before the first repeated pygame.KEYDOWN event will be sent. After that, another pygame.KEYDOWN event will be sent every interval milliseconds. If a delay value is provided and an interval value is not provided or is 0, then the interval will be set to the same value as delay.
To disable key repeat call this function with no arguments or with delay set to 0.
When pygame is initialized the key repeat is disabled.
Changed in pygame 2.0.0: A ValueError is now raised (instead of a pygame.error) if delay or interval is < 0.
Get the delay and interval keyboard repeat values. Refer to pygame.key.set_repeat() for a description of these values.
New in pygame 1.8.
Get the descriptive name of the button from a keyboard button id constant.
Get the key identifier code from the descriptive name of the key. This returns an integer matching one of the K_* keycodes. For example:
New in pygame 2.0.0.
Start receiving pygame.TEXTEDITING and pygame.TEXTINPUT events.
A pygame.TEXTEDITING event is received when an IME composition is started or changed. It contains the composition text, length, and editing start position within the composition (attributes text, length, and start, respectively). When the composition is committed (or non-IME input is received), a pygame.TEXTINPUT event is generated.
Text input events handling is on by default.
New in pygame 2.0.0.
Stop receiving pygame.TEXTEDITING and pygame.TEXTINPUT events.
Text input events handling is on by default
New in pygame 2.0.0.
This sets the rectangle used for typing with an IME. It controls where the candidate list will open, if supported.
New in pygame 2.0.0.


Returns True when the display window has keyboard focus from the system. If the display needs to ensure it does not lose keyboard focus, it can use pygame.event.set_grab() to grab all input.


Returns a single integer representing a bitmask of all the modifier keys being held. Using bitwise operators you can test if specific modifier keys are pressed.


Returns a sequence of boolean values representing the state of every key on the keyboard. Use the key constant values to index the array. A True value means the that button is pressed.
Note
Getting the list of pushed buttons with this function is not the proper way to handle text entry from the user. There is no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to pygame.key.get_pressed(). There is also no way to translate these pushed keys into a fully translated character value. See the pygame.KEYDOWN events on the pygame.event queue for this functionality.


Get the delay and interval keyboard repeat values. Refer to pygame.key.set_repeat() for a description of these values.
New in pygame 1.8.


Get the key identifier code from the descriptive name of the key. This returns an integer matching one of the K_* keycodes. For example:
New in pygame 2.0.0.


Get the descriptive name of the button from a keyboard button id constant.


Create a bitmask of the modifier key constants you want to impose on your program.


When the keyboard repeat is enabled, keys that are held down will generate multiple pygame.KEYDOWN events. The delay parameter is the number of milliseconds before the first repeated pygame.KEYDOWN event will be sent. After that, another pygame.KEYDOWN event will be sent every interval milliseconds. If a delay value is provided and an interval value is not provided or is 0, then the interval will be set to the same value as delay.
To disable key repeat call this function with no arguments or with delay set to 0.
When pygame is initialized the key repeat is disabled.
Changed in pygame 2.0.0: A ValueError is now raised (instead of a pygame.error) if delay or interval is < 0.


This sets the rectangle used for typing with an IME. It controls where the candidate list will open, if supported.
New in pygame 2.0.0.


Start receiving pygame.TEXTEDITING and pygame.TEXTINPUT events.
A pygame.TEXTEDITING event is received when an IME composition is started or changed. It contains the composition text, length, and editing start position within the composition (attributes text, length, and start, respectively). When the composition is committed (or non-IME input is received), a pygame.TEXTINPUT event is generated.
Text input events handling is on by default.
New in pygame 2.0.0.


Stop receiving pygame.TEXTEDITING and pygame.TEXTINPUT events.
Text input events handling is on by default
New in pygame 2.0.0.


This module contains various constants used by pygame. Its contents are automatically placed in the pygame module namespace. However, an application can use pygame.locals to include only the pygame constants with a from
pygame.locals import *.
Detailed descriptions of the various constants can be found throughout the pygame documentation. Here are the locations of some of them.


Useful for fast pixel perfect collision detection. A mask uses 1 bit per-pixel to store which parts collide.
New in pygame 1.8.
Creates a Mask object from the given surface by setting all the opaque pixels and not setting the transparent pixels.
If the surface uses a color-key, then it is used to decide which bits in the resulting mask are set. All the pixels that are not equal to the color-key are set and the pixels equal to the color-key are not set.
If a color-key is not used, then the alpha value of each pixel is used to decide which bits in the resulting mask are set. All the pixels that have an alpha value greater than the threshold parameter are set and the pixels with an alpha value less than or equal to the threshold are not set.
a newly created Mask object from the given surface
Mask
Note
This function is used to create the masks for pygame.sprite.collide_mask().
This is a more featureful method of getting a Mask from a surface.
If the optional othersurface is not used, all the pixels within the threshold of the color parameter are set in the resulting mask.
If the optional othersurface is used, every pixel in the first surface that is within the threshold of the corresponding pixel in othersurface is set in the resulting mask.
a newly created Mask object from the given surface
Mask
A Mask object is used to represent a 2D bitmask. Each bit in the mask represents a pixel. 1 is used to indicate a set bit and 0 is used to indicate an unset bit. Set bits in a mask can be used to detect collisions with other masks and their set bits.
A filled mask has all of its bits set to 1, conversely an unfilled/cleared/empty mask has all of its bits set to 0. Masks can be created unfilled (default) or filled by using the fill parameter. Masks can also be cleared or filled using the pygame.mask.Mask.clear() and pygame.mask.Mask.fill() methods respectively.
A mask's coordinates start in the top left corner at (0, 0) just like pygame.Surface. Individual bits can be accessed using the pygame.mask.Mask.get_at() and pygame.mask.Mask.set_at() methods.
The methods overlap(), overlap_area(), overlap_mask(), draw(), erase(), and convolve() use an offset parameter to indicate the offset of another mask's top left corner from the calling mask's top left corner. The calling mask's top left corner is considered to be the origin (0, 0). Offsets are a tuple or list of 2 integer values (x_offset, y_offset). Positive and negative offset values are supported.
a newly created Mask object
Mask
Changed in pygame 2.0.0: Shallow copy support added. The Mask class supports the special method __copy__() and shallow copying via copy.copy(mask).
Changed in pygame 2.0.0: Subclassing support added. The Mask class can be used as a base class.
Changed in pygame 1.9.5: Added support for keyword arguments.
Changed in pygame 1.9.5: Added the optional keyword parameter fill.
Changed in pygame 1.9.5: Added support for masks with a width and/or a height of 0.
Note
If a mask subclass needs to copy any instance specific attributes then it should override the __copy__() method. The overridden __copy__() method needs to call super().__copy__() and then copy the required data as in the following example code.
New in pygame 2.0.0.
Returns a new pygame.Rect() object based on the size of this mask. The rect's default position will be (0, 0) and its default width and height will be the same as this mask's. The rect's attributes can be altered via pygame.Rect() attribute keyword arguments/values passed into this method. As an example, a_mask.get_rect(center=(10, 5)) would create a pygame.Rect() based on the mask's size centered at the given position.
New in pygame 2.0.0.
None
NoneType
IndexError -- if the position is outside of the mask's bounds
Returns the first point of intersection encountered between this mask and othermask. A point of intersection is 2 overlapping set bits.
The current algorithm searches the overlapping area in sizeof(unsigned long int) * CHAR_BIT bit wide column blocks (the value of sizeof(unsigned long int) * CHAR_BIT is platform dependent, for clarity it will be referred to as W). Starting at the top left corner it checks bits 0 to W - 1 of the first row ((0, 0) to (W - 1, 0)) then continues to the next row ((0, 1) to (W - 1, 1)). Once this entire column block is checked, it continues to the next one (W to 2 * W - 1). This is repeated until it finds a point of intersection or the entire overlapping area is checked.
point of intersection or None if no intersection
tuple(int, int) or NoneType
Returns the number of overlapping set bits between between this mask and othermask.
This can be useful for collision detection. An approximate collision normal can be found by calculating the gradient of the overlapping area through the finite difference.
the number of overlapping set bits
int
Returns a Mask, the same size as this mask, containing the overlapping set bits between this mask and othermask.
a newly created Mask with the overlapping bits set
Mask
Sets all bits in the mask to 1.
Sets all bits in the mask to 0.
Flips all of the bits in the mask. All the set bits are cleared to 0 and all the unset bits are set to 1.
Creates a new Mask of the requested size with its bits scaled from this mask.
Performs a bitwise OR, drawing othermask onto this mask.
None
NoneType
Erases (clears) all bits set in othermask from this mask.
None
NoneType
Finds the centroid (the center mass of the set bits) for this mask.
Finds the approximate orientation (from -90 to 90 degrees) of the set bits in the mask. This works best if performed on a mask with only one connected component.
Note
See connected_component() for details on how a connected component is calculated.
Returns a list of points of the outline of the first connected component encountered in the mask. To find a connected component, the mask is searched per row (left to right) starting in the top left corner.
The every optional parameter skips set bits in the outline. For example, setting it to 10 would return a list of every 10th set bit in the outline.
Note
See connected_component() for details on how a connected component is calculated.
Convolve this mask with the given othermask.
a Mask with the (i - offset[0], j - offset[1]) bit set, if shifting othermask (such that its bottom right corner is at (i, j)) causes it to overlap with this mask
If an outputmask is specified, the output is drawn onto it and it is returned. Otherwise a mask of size (MAX(0, width + othermask's
width - 1), MAX(0, height + othermask's height - 1)) is created and returned.
Mask
A connected component is a group (1 or more) of connected set bits (orthogonally and diagonally). The SAUF algorithm, which checks 8 point connectivity, is used to find a connected component in the mask.
By default this method will return a Mask containing the largest connected component in the mask. Optionally, a bit coordinate can be specified and the connected component containing it will be returned. If the bit at the given location is not set, the returned Mask will be empty (no bits set).
If the pos parameter is provided then the mask returned will have the connected component that contains this position. An empty mask will be returned if the pos parameter selects an unset bit.
Provides a list containing a Mask object for each connected component.
Note
See connected_component() for details on how a connected component is calculated.
Provides a list containing a bounding rect for each connected component.
Note
See connected_component() for details on how a connected component is calculated.
Draws this mask on the given surface. Set bits (bits set to 1) and unset bits (bits set to 0) can be drawn onto a surface.
the surface parameter (or a newly created surface if no surface parameter was provided) with this mask drawn on it
Surface
ValueError -- if the setsurface parameter or unsetsurface parameter does not have the same format (bytesize/bitsize/alpha) as the surface parameter
Note
To skip drawing the set bits, both setsurface and setcolor must be None. The setsurface parameter defaults to None, but setcolor defaults to a color value and therefore must be set to None.
Note
To skip drawing the unset bits, both unsetsurface and unsetcolor must be None. The unsetsurface parameter defaults to None, but unsetcolor defaults to a color value and therefore must be set to None.
New in pygame 2.0.0.


Creates a Mask object from the given surface by setting all the opaque pixels and not setting the transparent pixels.
If the surface uses a color-key, then it is used to decide which bits in the resulting mask are set. All the pixels that are not equal to the color-key are set and the pixels equal to the color-key are not set.
If a color-key is not used, then the alpha value of each pixel is used to decide which bits in the resulting mask are set. All the pixels that have an alpha value greater than the threshold parameter are set and the pixels with an alpha value less than or equal to the threshold are not set.
a newly created Mask object from the given surface
Mask
Note
This function is used to create the masks for pygame.sprite.collide_mask().


This is a more featureful method of getting a Mask from a surface.
If the optional othersurface is not used, all the pixels within the threshold of the color parameter are set in the resulting mask.
If the optional othersurface is used, every pixel in the first surface that is within the threshold of the corresponding pixel in othersurface is set in the resulting mask.
a newly created Mask object from the given surface
Mask


A Mask object is used to represent a 2D bitmask. Each bit in the mask represents a pixel. 1 is used to indicate a set bit and 0 is used to indicate an unset bit. Set bits in a mask can be used to detect collisions with other masks and their set bits.
A filled mask has all of its bits set to 1, conversely an unfilled/cleared/empty mask has all of its bits set to 0. Masks can be created unfilled (default) or filled by using the fill parameter. Masks can also be cleared or filled using the pygame.mask.Mask.clear() and pygame.mask.Mask.fill() methods respectively.
A mask's coordinates start in the top left corner at (0, 0) just like pygame.Surface. Individual bits can be accessed using the pygame.mask.Mask.get_at() and pygame.mask.Mask.set_at() methods.
The methods overlap(), overlap_area(), overlap_mask(), draw(), erase(), and convolve() use an offset parameter to indicate the offset of another mask's top left corner from the calling mask's top left corner. The calling mask's top left corner is considered to be the origin (0, 0). Offsets are a tuple or list of 2 integer values (x_offset, y_offset). Positive and negative offset values are supported.
a newly created Mask object
Mask
Changed in pygame 2.0.0: Shallow copy support added. The Mask class supports the special method __copy__() and shallow copying via copy.copy(mask).
Changed in pygame 2.0.0: Subclassing support added. The Mask class can be used as a base class.
Changed in pygame 1.9.5: Added support for keyword arguments.
Changed in pygame 1.9.5: Added the optional keyword parameter fill.
Changed in pygame 1.9.5: Added support for masks with a width and/or a height of 0.
Note
If a mask subclass needs to copy any instance specific attributes then it should override the __copy__() method. The overridden __copy__() method needs to call super().__copy__() and then copy the required data as in the following example code.
New in pygame 2.0.0.
Returns a new pygame.Rect() object based on the size of this mask. The rect's default position will be (0, 0) and its default width and height will be the same as this mask's. The rect's attributes can be altered via pygame.Rect() attribute keyword arguments/values passed into this method. As an example, a_mask.get_rect(center=(10, 5)) would create a pygame.Rect() based on the mask's size centered at the given position.
New in pygame 2.0.0.
None
NoneType
IndexError -- if the position is outside of the mask's bounds
Returns the first point of intersection encountered between this mask and othermask. A point of intersection is 2 overlapping set bits.
The current algorithm searches the overlapping area in sizeof(unsigned long int) * CHAR_BIT bit wide column blocks (the value of sizeof(unsigned long int) * CHAR_BIT is platform dependent, for clarity it will be referred to as W). Starting at the top left corner it checks bits 0 to W - 1 of the first row ((0, 0) to (W - 1, 0)) then continues to the next row ((0, 1) to (W - 1, 1)). Once this entire column block is checked, it continues to the next one (W to 2 * W - 1). This is repeated until it finds a point of intersection or the entire overlapping area is checked.
point of intersection or None if no intersection
tuple(int, int) or NoneType
Returns the number of overlapping set bits between between this mask and othermask.
This can be useful for collision detection. An approximate collision normal can be found by calculating the gradient of the overlapping area through the finite difference.
the number of overlapping set bits
int
Returns a Mask, the same size as this mask, containing the overlapping set bits between this mask and othermask.
a newly created Mask with the overlapping bits set
Mask
Sets all bits in the mask to 1.
Sets all bits in the mask to 0.
Flips all of the bits in the mask. All the set bits are cleared to 0 and all the unset bits are set to 1.
Creates a new Mask of the requested size with its bits scaled from this mask.
Performs a bitwise OR, drawing othermask onto this mask.
None
NoneType
Erases (clears) all bits set in othermask from this mask.
None
NoneType
Finds the centroid (the center mass of the set bits) for this mask.
Finds the approximate orientation (from -90 to 90 degrees) of the set bits in the mask. This works best if performed on a mask with only one connected component.
Note
See connected_component() for details on how a connected component is calculated.
Returns a list of points of the outline of the first connected component encountered in the mask. To find a connected component, the mask is searched per row (left to right) starting in the top left corner.
The every optional parameter skips set bits in the outline. For example, setting it to 10 would return a list of every 10th set bit in the outline.
Note
See connected_component() for details on how a connected component is calculated.
Convolve this mask with the given othermask.
a Mask with the (i - offset[0], j - offset[1]) bit set, if shifting othermask (such that its bottom right corner is at (i, j)) causes it to overlap with this mask
If an outputmask is specified, the output is drawn onto it and it is returned. Otherwise a mask of size (MAX(0, width + othermask's
width - 1), MAX(0, height + othermask's height - 1)) is created and returned.
Mask
A connected component is a group (1 or more) of connected set bits (orthogonally and diagonally). The SAUF algorithm, which checks 8 point connectivity, is used to find a connected component in the mask.
By default this method will return a Mask containing the largest connected component in the mask. Optionally, a bit coordinate can be specified and the connected component containing it will be returned. If the bit at the given location is not set, the returned Mask will be empty (no bits set).
If the pos parameter is provided then the mask returned will have the connected component that contains this position. An empty mask will be returned if the pos parameter selects an unset bit.
Provides a list containing a Mask object for each connected component.
Note
See connected_component() for details on how a connected component is calculated.
Provides a list containing a bounding rect for each connected component.
Note
See connected_component() for details on how a connected component is calculated.
Draws this mask on the given surface. Set bits (bits set to 1) and unset bits (bits set to 0) can be drawn onto a surface.
the surface parameter (or a newly created surface if no surface parameter was provided) with this mask drawn on it
Surface
ValueError -- if the setsurface parameter or unsetsurface parameter does not have the same format (bytesize/bitsize/alpha) as the surface parameter
Note
To skip drawing the set bits, both setsurface and setcolor must be None. The setsurface parameter defaults to None, but setcolor defaults to a color value and therefore must be set to None.
Note
To skip drawing the unset bits, both unsetsurface and unsetcolor must be None. The unsetsurface parameter defaults to None, but unsetcolor defaults to a color value and therefore must be set to None.
New in pygame 2.0.0.


Finds the approximate orientation (from -90 to 90 degrees) of the set bits in the mask. This works best if performed on a mask with only one connected component.
Note
See connected_component() for details on how a connected component is calculated.


Finds the centroid (the center mass of the set bits) for this mask.


A connected component is a group (1 or more) of connected set bits (orthogonally and diagonally). The SAUF algorithm, which checks 8 point connectivity, is used to find a connected component in the mask.
By default this method will return a Mask containing the largest connected component in the mask. Optionally, a bit coordinate can be specified and the connected component containing it will be returned. If the bit at the given location is not set, the returned Mask will be empty (no bits set).
If the pos parameter is provided then the mask returned will have the connected component that contains this position. An empty mask will be returned if the pos parameter selects an unset bit.


Provides a list containing a Mask object for each connected component.
Note
See connected_component() for details on how a connected component is calculated.


Convolve this mask with the given othermask.
a Mask with the (i - offset[0], j - offset[1]) bit set, if shifting othermask (such that its bottom right corner is at (i, j)) causes it to overlap with this mask
If an outputmask is specified, the output is drawn onto it and it is returned. Otherwise a mask of size (MAX(0, width + othermask's
width - 1), MAX(0, height + othermask's height - 1)) is created and returned.
Mask


Note
If a mask subclass needs to copy any instance specific attributes then it should override the __copy__() method. The overridden __copy__() method needs to call super().__copy__() and then copy the required data as in the following example code.
New in pygame 2.0.0.


Performs a bitwise OR, drawing othermask onto this mask.
None
NoneType


Erases (clears) all bits set in othermask from this mask.
None
NoneType


Provides a list containing a bounding rect for each connected component.
Note
See connected_component() for details on how a connected component is calculated.


Returns a new pygame.Rect() object based on the size of this mask. The rect's default position will be (0, 0) and its default width and height will be the same as this mask's. The rect's attributes can be altered via pygame.Rect() attribute keyword arguments/values passed into this method. As an example, a_mask.get_rect(center=(10, 5)) would create a pygame.Rect() based on the mask's size centered at the given position.
New in pygame 2.0.0.


Flips all of the bits in the mask. All the set bits are cleared to 0 and all the unset bits are set to 1.


Returns a list of points of the outline of the first connected component encountered in the mask. To find a connected component, the mask is searched per row (left to right) starting in the top left corner.
The every optional parameter skips set bits in the outline. For example, setting it to 10 would return a list of every 10th set bit in the outline.
Note
See connected_component() for details on how a connected component is calculated.


Returns the first point of intersection encountered between this mask and othermask. A point of intersection is 2 overlapping set bits.
The current algorithm searches the overlapping area in sizeof(unsigned long int) * CHAR_BIT bit wide column blocks (the value of sizeof(unsigned long int) * CHAR_BIT is platform dependent, for clarity it will be referred to as W). Starting at the top left corner it checks bits 0 to W - 1 of the first row ((0, 0) to (W - 1, 0)) then continues to the next row ((0, 1) to (W - 1, 1)). Once this entire column block is checked, it continues to the next one (W to 2 * W - 1). This is repeated until it finds a point of intersection or the entire overlapping area is checked.
point of intersection or None if no intersection
tuple(int, int) or NoneType


Returns the number of overlapping set bits between between this mask and othermask.
This can be useful for collision detection. An approximate collision normal can be found by calculating the gradient of the overlapping area through the finite difference.
the number of overlapping set bits
int


Returns a Mask, the same size as this mask, containing the overlapping set bits between this mask and othermask.
a newly created Mask with the overlapping bits set
Mask


Creates a new Mask of the requested size with its bits scaled from this mask.


None
NoneType
IndexError -- if the position is outside of the mask's bounds


Draws this mask on the given surface. Set bits (bits set to 1) and unset bits (bits set to 0) can be drawn onto a surface.
the surface parameter (or a newly created surface if no surface parameter was provided) with this mask drawn on it
Surface
ValueError -- if the setsurface parameter or unsetsurface parameter does not have the same format (bytesize/bitsize/alpha) as the surface parameter
Note
To skip drawing the set bits, both setsurface and setcolor must be None. The setsurface parameter defaults to None, but setcolor defaults to a color value and therefore must be set to None.
Note
To skip drawing the unset bits, both unsetsurface and unsetcolor must be None. The unsetsurface parameter defaults to None, but unsetcolor defaults to a color value and therefore must be set to None.
New in pygame 2.0.0.


The pygame math module currently provides Vector classes in two and three dimensions, Vector2 and Vector3 respectively.
They support the following numerical operations: vec+vec, vec-vec, vec*number, number*vec, vec/number, vec//number, vec+=vec, vec-=vec, vec*=number, vec/=number, vec//=number.
All these operations will be performed elementwise. In addition vec*vec will perform a scalar-product (a.k.a. dot-product). If you want to multiply every element from vector v with every element from vector w you can use the elementwise method: v.elementwise() * w
The coordinates of a vector can be retrieved or set using attributes or subscripts
Multiple coordinates can be set using slices or swizzling
New in pygame 1.9.2pre.
Changed in pygame 1.9.4: Removed experimental notice.
Changed in pygame 1.9.4: Allow scalar construction like GLSL Vector2(2) == Vector2(2.0, 2.0)
Changed in pygame 1.9.4: pygame.math required import. More convenient pygame.Vector2 and pygame.Vector3.
Some general information about the Vector2 class.
calculates the third component of the cross-product.
calculates the magnitude of the vector which follows from the theorem: vec.magnitude() == math.sqrt(vec.x**2 + vec.y**2)
calculates the magnitude of the vector which follows from the theorem: vec.magnitude_squared() == vec.x**2 + vec.y**2. This is faster than vec.magnitude() because it avoids the square root.
calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length() == math.sqrt(vec.x**2 + vec.y**2)
calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length_squared() == vec.x**2 + vec.y**2. This is faster than vec.length() because it avoids the square root.
Returns a new vector that has length equal to 1 and the same direction as self.
Normalizes the vector so that it has length equal to 1. The direction of the vector is not changed.
Returns True if the vector has length equal to 1. Otherwise it returns False.
Scales the vector so that it has the given length. The direction of the vector is not changed. You can also scale to length 0. If the vector is the zero vector (i.e. has length 0 thus no direction) a ValueError is raised.
Returns a new vector that points in the direction as if self would bounce of a surface characterized by the given surface normal. The length of the new vector is the same as self's.
Changes the direction of self as if it would have been reflected of a surface with the given surface normal.
Returns a Vector which is a linear interpolation between self and the given Vector. The second parameter determines how far between self and other the result is going to be. It must be a value between 0 and 1 where 0 means self and 1 means other will be returned.
Calculates the spherical interpolation from self to the given Vector. The second argument - often called t - must be in the range [-1, 1]. It parametrizes where - in between the two vectors - the result should be. If a negative value is given the interpolation will not take the complement of the shortest path.
Applies the following operation to each element of the vector.
Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in degrees.
Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in radians.
New in pygame 2.0.0.
Rotates the vector counterclockwise by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.
Returns the angle between self and the given vector.
Returns a tuple (r, phi) where r is the radial distance, and phi is the azimuthal angle.
Sets x and y from a tuple (r, phi) where r is the radial distance, and phi is the azimuthal angle.
Sets coordinates x and y in place.
New in pygame 1.9.5.
Some general information about the Vector3 class.
calculates the cross-product.
calculates the magnitude of the vector which follows from the theorem: vec.magnitude() == math.sqrt(vec.x**2 + vec.y**2 + vec.z**2)
calculates the magnitude of the vector which follows from the theorem: vec.magnitude_squared() == vec.x**2 + vec.y**2 + vec.z**2. This is faster than vec.magnitude() because it avoids the square root.
calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length() == math.sqrt(vec.x**2 + vec.y**2 + vec.z**2)
calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length_squared() == vec.x**2 + vec.y**2 + vec.z**2. This is faster than vec.length() because it avoids the square root.
Returns a new vector that has length equal to 1 and the same direction as self.
Normalizes the vector so that it has length equal to 1. The direction of the vector is not changed.
Returns True if the vector has length equal to 1. Otherwise it returns False.
Scales the vector so that it has the given length. The direction of the vector is not changed. You can also scale to length 0. If the vector is the zero vector (i.e. has length 0 thus no direction) a ValueError is raised.
Returns a new vector that points in the direction as if self would bounce of a surface characterized by the given surface normal. The length of the new vector is the same as self's.
Changes the direction of self as if it would have been reflected of a surface with the given surface normal.
Returns a Vector which is a linear interpolation between self and the given Vector. The second parameter determines how far between self an other the result is going to be. It must be a value between 0 and 1, where 0 means self and 1 means other will be returned.
Calculates the spherical interpolation from self to the given Vector. The second argument - often called t - must be in the range [-1, 1]. It parametrizes where - in between the two vectors - the result should be. If a negative value is given the interpolation will not take the complement of the shortest path.
Applies the following operation to each element of the vector.
Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in degrees around the given axis.
Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in radians around the given axis.
New in pygame 2.0.0.
Rotates the vector counterclockwise around the given axis by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise around the given axis by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.
Returns a vector which has the same length as self but is rotated counterclockwise around the x-axis by the given angle in degrees.
Returns a vector which has the same length as self but is rotated counterclockwise around the x-axis by the given angle in radians.
New in pygame 2.0.0.
Rotates the vector counterclockwise around the x-axis by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise around the x-axis by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.
Returns a vector which has the same length as self but is rotated counterclockwise around the y-axis by the given angle in degrees.
Returns a vector which has the same length as self but is rotated counterclockwise around the y-axis by the given angle in radians.
New in pygame 2.0.0.
Rotates the vector counterclockwise around the y-axis by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise around the y-axis by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.
Returns a vector which has the same length as self but is rotated counterclockwise around the z-axis by the given angle in degrees.
Returns a vector which has the same length as self but is rotated counterclockwise around the z-axis by the given angle in radians.
New in pygame 2.0.0.
Rotates the vector counterclockwise around the z-axis by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise around the z-axis by the given angle in radians. The length of the vector is not changed.
Returns the angle between self and the given vector.
Returns a tuple (r, theta, phi) where r is the radial distance, theta is the inclination angle and phi is the azimuthal angle.
Sets x, y and z from a tuple (r, theta, phi) where r is the radial distance, theta is the inclination angle and phi is the azimuthal angle.
Sets coordinates x, y, and z in place.
New in pygame 1.9.5.
DEPRECATED: Not needed anymore. Will be removed in a later version.
Enables swizzling for all vectors until disable_swizzling() is called. By default swizzling is disabled.
Lets you get or set multiple coordinates as one attribute, eg vec.xyz = 1, 2, 3.
DEPRECATED: Not needed anymore. Will be removed in a later version.
Disables swizzling for all vectors until enable_swizzling() is called. By default swizzling is disabled.


DEPRECATED: Not needed anymore. Will be removed in a later version.
Disables swizzling for all vectors until enable_swizzling() is called. By default swizzling is disabled.


DEPRECATED: Not needed anymore. Will be removed in a later version.
Enables swizzling for all vectors until disable_swizzling() is called. By default swizzling is disabled.
Lets you get or set multiple coordinates as one attribute, eg vec.xyz = 1, 2, 3.


Some general information about the Vector2 class.
calculates the third component of the cross-product.
calculates the magnitude of the vector which follows from the theorem: vec.magnitude() == math.sqrt(vec.x**2 + vec.y**2)
calculates the magnitude of the vector which follows from the theorem: vec.magnitude_squared() == vec.x**2 + vec.y**2. This is faster than vec.magnitude() because it avoids the square root.
calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length() == math.sqrt(vec.x**2 + vec.y**2)
calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length_squared() == vec.x**2 + vec.y**2. This is faster than vec.length() because it avoids the square root.
Returns a new vector that has length equal to 1 and the same direction as self.
Normalizes the vector so that it has length equal to 1. The direction of the vector is not changed.
Returns True if the vector has length equal to 1. Otherwise it returns False.
Scales the vector so that it has the given length. The direction of the vector is not changed. You can also scale to length 0. If the vector is the zero vector (i.e. has length 0 thus no direction) a ValueError is raised.
Returns a new vector that points in the direction as if self would bounce of a surface characterized by the given surface normal. The length of the new vector is the same as self's.
Changes the direction of self as if it would have been reflected of a surface with the given surface normal.
Returns a Vector which is a linear interpolation between self and the given Vector. The second parameter determines how far between self and other the result is going to be. It must be a value between 0 and 1 where 0 means self and 1 means other will be returned.
Calculates the spherical interpolation from self to the given Vector. The second argument - often called t - must be in the range [-1, 1]. It parametrizes where - in between the two vectors - the result should be. If a negative value is given the interpolation will not take the complement of the shortest path.
Applies the following operation to each element of the vector.
Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in degrees.
Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in radians.
New in pygame 2.0.0.
Rotates the vector counterclockwise by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.
Returns the angle between self and the given vector.
Returns a tuple (r, phi) where r is the radial distance, and phi is the azimuthal angle.
Sets x and y from a tuple (r, phi) where r is the radial distance, and phi is the azimuthal angle.
Sets coordinates x and y in place.
New in pygame 1.9.5.


Returns the angle between self and the given vector.


Returns a tuple (r, phi) where r is the radial distance, and phi is the azimuthal angle.


calculates the third component of the cross-product.


Applies the following operation to each element of the vector.


Sets x and y from a tuple (r, phi) where r is the radial distance, and phi is the azimuthal angle.


Returns True if the vector has length equal to 1. Otherwise it returns False.


calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length() == math.sqrt(vec.x**2 + vec.y**2)


calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length_squared() == vec.x**2 + vec.y**2. This is faster than vec.length() because it avoids the square root.


Returns a Vector which is a linear interpolation between self and the given Vector. The second parameter determines how far between self and other the result is going to be. It must be a value between 0 and 1 where 0 means self and 1 means other will be returned.


calculates the magnitude of the vector which follows from the theorem: vec.magnitude() == math.sqrt(vec.x**2 + vec.y**2)


calculates the magnitude of the vector which follows from the theorem: vec.magnitude_squared() == vec.x**2 + vec.y**2. This is faster than vec.magnitude() because it avoids the square root.


Returns a new vector that has length equal to 1 and the same direction as self.


Normalizes the vector so that it has length equal to 1. The direction of the vector is not changed.


Returns a new vector that points in the direction as if self would bounce of a surface characterized by the given surface normal. The length of the new vector is the same as self's.


Changes the direction of self as if it would have been reflected of a surface with the given surface normal.


Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in degrees.


Rotates the vector counterclockwise by the given angle in degrees. The length of the vector is not changed.


Rotates the vector counterclockwise by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.


Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in radians.
New in pygame 2.0.0.


Scales the vector so that it has the given length. The direction of the vector is not changed. You can also scale to length 0. If the vector is the zero vector (i.e. has length 0 thus no direction) a ValueError is raised.


Calculates the spherical interpolation from self to the given Vector. The second argument - often called t - must be in the range [-1, 1]. It parametrizes where - in between the two vectors - the result should be. If a negative value is given the interpolation will not take the complement of the shortest path.


Sets coordinates x and y in place.
New in pygame 1.9.5.


Some general information about the Vector3 class.
calculates the cross-product.
calculates the magnitude of the vector which follows from the theorem: vec.magnitude() == math.sqrt(vec.x**2 + vec.y**2 + vec.z**2)
calculates the magnitude of the vector which follows from the theorem: vec.magnitude_squared() == vec.x**2 + vec.y**2 + vec.z**2. This is faster than vec.magnitude() because it avoids the square root.
calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length() == math.sqrt(vec.x**2 + vec.y**2 + vec.z**2)
calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length_squared() == vec.x**2 + vec.y**2 + vec.z**2. This is faster than vec.length() because it avoids the square root.
Returns a new vector that has length equal to 1 and the same direction as self.
Normalizes the vector so that it has length equal to 1. The direction of the vector is not changed.
Returns True if the vector has length equal to 1. Otherwise it returns False.
Scales the vector so that it has the given length. The direction of the vector is not changed. You can also scale to length 0. If the vector is the zero vector (i.e. has length 0 thus no direction) a ValueError is raised.
Returns a new vector that points in the direction as if self would bounce of a surface characterized by the given surface normal. The length of the new vector is the same as self's.
Changes the direction of self as if it would have been reflected of a surface with the given surface normal.
Returns a Vector which is a linear interpolation between self and the given Vector. The second parameter determines how far between self an other the result is going to be. It must be a value between 0 and 1, where 0 means self and 1 means other will be returned.
Calculates the spherical interpolation from self to the given Vector. The second argument - often called t - must be in the range [-1, 1]. It parametrizes where - in between the two vectors - the result should be. If a negative value is given the interpolation will not take the complement of the shortest path.
Applies the following operation to each element of the vector.
Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in degrees around the given axis.
Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in radians around the given axis.
New in pygame 2.0.0.
Rotates the vector counterclockwise around the given axis by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise around the given axis by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.
Returns a vector which has the same length as self but is rotated counterclockwise around the x-axis by the given angle in degrees.
Returns a vector which has the same length as self but is rotated counterclockwise around the x-axis by the given angle in radians.
New in pygame 2.0.0.
Rotates the vector counterclockwise around the x-axis by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise around the x-axis by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.
Returns a vector which has the same length as self but is rotated counterclockwise around the y-axis by the given angle in degrees.
Returns a vector which has the same length as self but is rotated counterclockwise around the y-axis by the given angle in radians.
New in pygame 2.0.0.
Rotates the vector counterclockwise around the y-axis by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise around the y-axis by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.
Returns a vector which has the same length as self but is rotated counterclockwise around the z-axis by the given angle in degrees.
Returns a vector which has the same length as self but is rotated counterclockwise around the z-axis by the given angle in radians.
New in pygame 2.0.0.
Rotates the vector counterclockwise around the z-axis by the given angle in degrees. The length of the vector is not changed.
Rotates the vector counterclockwise around the z-axis by the given angle in radians. The length of the vector is not changed.
Returns the angle between self and the given vector.
Returns a tuple (r, theta, phi) where r is the radial distance, theta is the inclination angle and phi is the azimuthal angle.
Sets x, y and z from a tuple (r, theta, phi) where r is the radial distance, theta is the inclination angle and phi is the azimuthal angle.
Sets coordinates x, y, and z in place.
New in pygame 1.9.5.


Returns the angle between self and the given vector.


Returns a tuple (r, theta, phi) where r is the radial distance, theta is the inclination angle and phi is the azimuthal angle.


Applies the following operation to each element of the vector.


Sets x, y and z from a tuple (r, theta, phi) where r is the radial distance, theta is the inclination angle and phi is the azimuthal angle.


Returns True if the vector has length equal to 1. Otherwise it returns False.


calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length() == math.sqrt(vec.x**2 + vec.y**2 + vec.z**2)


calculates the Euclidean length of the vector which follows from the Pythagorean theorem: vec.length_squared() == vec.x**2 + vec.y**2 + vec.z**2. This is faster than vec.length() because it avoids the square root.


Returns a Vector which is a linear interpolation between self and the given Vector. The second parameter determines how far between self an other the result is going to be. It must be a value between 0 and 1, where 0 means self and 1 means other will be returned.


calculates the magnitude of the vector which follows from the theorem: vec.magnitude() == math.sqrt(vec.x**2 + vec.y**2 + vec.z**2)


calculates the magnitude of the vector which follows from the theorem: vec.magnitude_squared() == vec.x**2 + vec.y**2 + vec.z**2. This is faster than vec.magnitude() because it avoids the square root.


Returns a new vector that has length equal to 1 and the same direction as self.


Normalizes the vector so that it has length equal to 1. The direction of the vector is not changed.


Returns a new vector that points in the direction as if self would bounce of a surface characterized by the given surface normal. The length of the new vector is the same as self's.


Changes the direction of self as if it would have been reflected of a surface with the given surface normal.


Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in degrees around the given axis.


Rotates the vector counterclockwise around the given axis by the given angle in degrees. The length of the vector is not changed.


Rotates the vector counterclockwise around the given axis by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.


Returns a vector which has the same length as self but is rotated counterclockwise by the given angle in radians around the given axis.
New in pygame 2.0.0.


Returns a vector which has the same length as self but is rotated counterclockwise around the x-axis by the given angle in degrees.


Rotates the vector counterclockwise around the x-axis by the given angle in degrees. The length of the vector is not changed.


Rotates the vector counterclockwise around the x-axis by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.


Returns a vector which has the same length as self but is rotated counterclockwise around the x-axis by the given angle in radians.
New in pygame 2.0.0.


Returns a vector which has the same length as self but is rotated counterclockwise around the y-axis by the given angle in degrees.


Rotates the vector counterclockwise around the y-axis by the given angle in degrees. The length of the vector is not changed.


Rotates the vector counterclockwise around the y-axis by the given angle in radians. The length of the vector is not changed.
New in pygame 2.0.0.


Returns a vector which has the same length as self but is rotated counterclockwise around the y-axis by the given angle in radians.
New in pygame 2.0.0.


Returns a vector which has the same length as self but is rotated counterclockwise around the z-axis by the given angle in degrees.


Rotates the vector counterclockwise around the z-axis by the given angle in degrees. The length of the vector is not changed.


Rotates the vector counterclockwise around the z-axis by the given angle in radians. The length of the vector is not changed.


Returns a vector which has the same length as self but is rotated counterclockwise around the z-axis by the given angle in radians.
New in pygame 2.0.0.


Scales the vector so that it has the given length. The direction of the vector is not changed. You can also scale to length 0. If the vector is the zero vector (i.e. has length 0 thus no direction) a ValueError is raised.


Calculates the spherical interpolation from self to the given Vector. The second argument - often called t - must be in the range [-1, 1]. It parametrizes where - in between the two vectors - the result should be. If a negative value is given the interpolation will not take the complement of the shortest path.


Sets coordinates x, y, and z in place.
New in pygame 1.9.5.


New in pygame 1.9.0.
The midi module can send output to midi devices and get input from midi devices. It can also list midi devices on the system.
The midi module supports real and virtual midi devices.
It uses the portmidi library. Is portable to which ever platforms portmidi supports (currently Windows, Mac OS X, and Linux).
This uses pyportmidi for now, but may use its own bindings at some point in the future. The pyportmidi bindings are included with pygame.
New in pygame 2.0.0.
These are pygame events (pygame.event) reserved for midi use. The MIDIIN event is used by pygame.midi.midis2events() when converting midi events to pygame events.
Initializes the pygame.midi module. Must be called before using the pygame.midi module.
It is safe to call this more than once.
Uninitializes the pygame.midi module. If pygame.midi.init() was called to initialize the pygame.midi module, then this function will be called automatically when your program exits.
It is safe to call this function more than once.
Gets the initialization state of the pygame.midi module.
New in pygame 1.9.5.
PortMidi attempts to close open streams when the application exits.
Note
This is particularly difficult under Windows.
Used to indicate if any data exists.
Reads from the input buffer and gives back midi events.
The buffer_size specifies the number of output events to be buffered waiting for output. In some cases (see below) PortMidi does not buffer output at all and merely passes data to a lower-level API, in which case buffersize is ignored.
latency is the delay in milliseconds applied to timestamps to determine when the output should actually occur. If latency is <<0, 0 is assumed.
If latency is zero, timestamps are ignored and all output is delivered immediately. If latency is greater than zero, output is delayed until the message timestamp plus the latency. In some cases, PortMidi can obtain better timing than your application by passing timestamps along to the device driver or hardware. Latency may also help you to synchronize midi data to audio data by matching midi latency to the audio buffer latency.
Note
Time is measured relative to the time source indicated by time_proc. Timestamps are absolute, not relative delays or offsets.
The caller should immediately close the output port; this call may result in transmission of a partial midi message. There is no abort for Midi input because the user can simply ignore messages in the buffer and close an input device at any time.
PortMidi attempts to close open streams when the application exits.
Note
This is particularly difficult under Windows.
Turn a note off in the output stream. The note must already be on for this to work correctly.
Turn a note on in the output stream. The note must already be off for this to work correctly.
Select an instrument.
Adjust the pitch of a channel. The value is a signed integer from -8192 to +8191. For example, 0 means "no change", +4096 is typically a semitone higher, and -8192 is 1 whole tone lower (though the musical range corresponding to the pitch bend range can also be changed in some synthesizers).
If no value is given, the pitch bend is returned to "no change".
New in pygame 1.9.4.
Writes series of MIDI information in the form of a list.
Example:
Note
Output MIDI information of 3 bytes or less. The data fields are optional and assumed to be 0 if omitted.
Examples of status byte values:
Example:
Writes a timestamped system-exclusive midi message.
Example:
Device ids range from 0 to get_count() - 1
The following describes the usage details for this function and the get_default_output_id() function.
Return the default device ID or -1 if there are no devices. The result can be passed to the Input/Output class.
On a PC the user can specify a default device by setting an environment variable. To use device #1, for example:
The user should first determine the available device ID by using the supplied application "testin" or "testout".
In general, the registry is a better place for this kind of info. With USB devices that can come and go, using integers is not very reliable for device identification. Under Windows, if PM_RECOMMENDED_INPUT_DEVICE (or PM_RECOMMENDED_OUTPUT_DEVICE) is NOT found in the environment, then the default device is obtained by looking for a string in the registry under:
The number of the first device with a substring that matches the string exactly is returned. For example, if the string in the registry is "USB" and device 1 is named "In USB MidiSport 1x1", then that will be the default input because it contains the string "USB".
In addition to the name, get_device_info() returns "interf", which is the interface name. The "interface" is the underlying software system or API used by PortMidi to access devices. Supported interfaces:
To specify both the interface and the device name in the registry, separate the two with a comma and a space. The string before the comma must be a substring of the "interf" string and the string after the space must be a substring of the "name" name string in order to match the device. e.g.:
Note
In the current release, the default is simply the first device (the input or output device with the lowest PmDeviceID).
See get_default_input_id() for usage details.
Gets the device info for a given id.
Takes a sequence of midi events and returns list of pygame events.
The midi_events data is expected to be a sequence of ((status, data1, data2, data3), timestamp) midi events (all values required).
The time is reset to 0 when the pygame.midi module is initialized.
example:
New in pygame 1.9.5.
example:
New in pygame 1.9.5.
example:
New in pygame 1.9.5.


Device ids range from 0 to get_count() - 1


The following describes the usage details for this function and the get_default_output_id() function.
Return the default device ID or -1 if there are no devices. The result can be passed to the Input/Output class.
On a PC the user can specify a default device by setting an environment variable. To use device #1, for example:
The user should first determine the available device ID by using the supplied application "testin" or "testout".
In general, the registry is a better place for this kind of info. With USB devices that can come and go, using integers is not very reliable for device identification. Under Windows, if PM_RECOMMENDED_INPUT_DEVICE (or PM_RECOMMENDED_OUTPUT_DEVICE) is NOT found in the environment, then the default device is obtained by looking for a string in the registry under:
The number of the first device with a substring that matches the string exactly is returned. For example, if the string in the registry is "USB" and device 1 is named "In USB MidiSport 1x1", then that will be the default input because it contains the string "USB".
In addition to the name, get_device_info() returns "interf", which is the interface name. The "interface" is the underlying software system or API used by PortMidi to access devices. Supported interfaces:
To specify both the interface and the device name in the registry, separate the two with a comma and a space. The string before the comma must be a substring of the "interf" string and the string after the space must be a substring of the "name" name string in order to match the device. e.g.:
Note
In the current release, the default is simply the first device (the input or output device with the lowest PmDeviceID).


See get_default_input_id() for usage details.


Gets the initialization state of the pygame.midi module.
New in pygame 1.9.5.


Initializes the pygame.midi module. Must be called before using the pygame.midi module.
It is safe to call this more than once.


PortMidi attempts to close open streams when the application exits.
Note
This is particularly difficult under Windows.
Used to indicate if any data exists.
Reads from the input buffer and gives back midi events.


PortMidi attempts to close open streams when the application exits.
Note
This is particularly difficult under Windows.


Reads from the input buffer and gives back midi events.


Takes a sequence of midi events and returns list of pygame events.
The midi_events data is expected to be a sequence of ((status, data1, data2, data3), timestamp) midi events (all values required).


The buffer_size specifies the number of output events to be buffered waiting for output. In some cases (see below) PortMidi does not buffer output at all and merely passes data to a lower-level API, in which case buffersize is ignored.
latency is the delay in milliseconds applied to timestamps to determine when the output should actually occur. If latency is <<0, 0 is assumed.
If latency is zero, timestamps are ignored and all output is delivered immediately. If latency is greater than zero, output is delayed until the message timestamp plus the latency. In some cases, PortMidi can obtain better timing than your application by passing timestamps along to the device driver or hardware. Latency may also help you to synchronize midi data to audio data by matching midi latency to the audio buffer latency.
Note
Time is measured relative to the time source indicated by time_proc. Timestamps are absolute, not relative delays or offsets.
The caller should immediately close the output port; this call may result in transmission of a partial midi message. There is no abort for Midi input because the user can simply ignore messages in the buffer and close an input device at any time.
PortMidi attempts to close open streams when the application exits.
Note
This is particularly difficult under Windows.
Turn a note off in the output stream. The note must already be on for this to work correctly.
Turn a note on in the output stream. The note must already be off for this to work correctly.
Select an instrument.
Adjust the pitch of a channel. The value is a signed integer from -8192 to +8191. For example, 0 means "no change", +4096 is typically a semitone higher, and -8192 is 1 whole tone lower (though the musical range corresponding to the pitch bend range can also be changed in some synthesizers).
If no value is given, the pitch bend is returned to "no change".
New in pygame 1.9.4.
Writes series of MIDI information in the form of a list.
Example:
Note
Output MIDI information of 3 bytes or less. The data fields are optional and assumed to be 0 if omitted.
Examples of status byte values:
Example:
Writes a timestamped system-exclusive midi message.
Example:


The caller should immediately close the output port; this call may result in transmission of a partial midi message. There is no abort for Midi input because the user can simply ignore messages in the buffer and close an input device at any time.


Turn a note off in the output stream. The note must already be on for this to work correctly.


Turn a note on in the output stream. The note must already be off for this to work correctly.


Adjust the pitch of a channel. The value is a signed integer from -8192 to +8191. For example, 0 means "no change", +4096 is typically a semitone higher, and -8192 is 1 whole tone lower (though the musical range corresponding to the pitch bend range can also be changed in some synthesizers).
If no value is given, the pitch bend is returned to "no change".
New in pygame 1.9.4.


Writes series of MIDI information in the form of a list.
Example:
Note


Output MIDI information of 3 bytes or less. The data fields are optional and assumed to be 0 if omitted.
Examples of status byte values:
Example:


Writes a timestamped system-exclusive midi message.
Example:


Uninitializes the pygame.midi module. If pygame.midi.init() was called to initialize the pygame.midi module, then this function will be called automatically when your program exits.
It is safe to call this function more than once.


The time is reset to 0 when the pygame.midi module is initialized.


This module contains classes for loading Sound objects and controlling playback. The mixer module is optional and depends on SDL_mixer. Your program should test that pygame.mixer is available and initialized before using it.
The mixer module has a limited number of channels for playback of sounds. Usually programs tell pygame to start playing audio and it selects an available channel automatically. The default is 8 simultaneous channels, but complex programs can get more precise control over the number of channels and their use.
All sound playback is mixed in background threads. When you begin to play a Sound object, it will return immediately while the sound continues to play. A single Sound object can also be actively played back multiple times.
The mixer also has a special streaming channel. This is for music playback and is accessed through the pygame.mixer.music module.
The mixer module must be initialized like other pygame modules, but it has some extra conditions. The pygame.mixer.init() function takes several optional arguments to control the playback rate and sample size. Pygame will default to reasonable values, but pygame cannot perform Sound resampling, so the mixer should be initialized to match the values of your audio resources.
NOTE: For less laggy sound use a smaller buffer size. The default is set to reduce the chance of scratchy sounds on some computers. You can change the default buffer by calling pygame.mixer.pre_init() before pygame.mixer.init() or pygame.init() is called. For example: pygame.mixer.pre_init(44100,-16,2, 1024)
Initialize the mixer module for Sound loading and playback. The default arguments can be overridden to provide specific audio mixing. Keyword arguments are accepted. For backward compatibility where an argument is set zero the default value is used (possible changed by a pre_init call).
The size argument represents how many bits are used for each audio sample. If the value is negative then signed sample values will be used. Positive values mean unsigned audio samples will be used. An invalid value raises an exception.
The channels argument is used to specify whether to use mono or stereo. 1 for mono and 2 for stereo.
The buffer argument controls the number of internal samples used in the sound mixer. The default value should work for most cases. It can be lowered to reduce latency, but sound dropout may occur. It can be raised to larger values to ensure playback never skips, but it will impose latency on sound playback. The buffer size must be a power of two (if not it is rounded up to the next nearest power of 2).
Some platforms require the pygame.mixer module to be initialized after the display modules have initialized. The top level pygame.init() takes care of this automatically, but cannot pass any arguments to the mixer init. To solve this, mixer has a function pygame.mixer.pre_init() to set the proper defaults before the toplevel init is used.
When using allowedchanges=0 it will convert the samples at runtime to match what the hardware supports. For example a sound card may not support 16bit sound samples, so instead it will use 8bit samples internally. If AUDIO_ALLOW_FORMAT_CHANGE is supplied, then the requested format will change to the closest that SDL2 supports.
Apart from 0, allowedchanged accepts the following constants ORed together:
It is safe to call this more than once, but after the mixer is initialized you cannot change the playback arguments without first calling pygame.mixer.quit().
Changed in pygame 1.8: The default buffersize was changed from 1024 to 3072.
Changed in pygame 1.9.1: The default buffersize was changed from 3072 to 4096.
Changed in pygame 2.0.0: The default buffersize was changed from 4096 to 512. The default frequency changed to 44100 from 22050.
Changed in pygame 2.0.0: size can be 32 (32bit floats).
Changed in pygame 2.0.0: channels can also be 4 or 6.
New in pygame 2.0.0: allowedchanges argument added
Call pre_init to change the defaults used when the real pygame.mixer.init() is called. Keyword arguments are accepted. The best way to set custom mixer playback values is to call pygame.mixer.pre_init() before calling the top level pygame.init(). For backward compatibility argument values of zero are replaced with the startup defaults.
Changed in pygame 1.8: The default buffersize was changed from 1024 to 3072.
Changed in pygame 1.9.1: The default buffersize was changed from 3072 to 4096.
Changed in pygame 2.0.0: The default buffersize was changed from 4096 to 512. The default frequency changed to 44100 from 22050.
This will uninitialize pygame.mixer. All playback will stop and any loaded Sound objects may not be compatible with the mixer if it is reinitialized later.
If the mixer is initialized, this returns the playback arguments it is using. If the mixer has not been initialized this returns None.
This will stop all playback of all active mixer channels.
This will temporarily stop all playback on the active mixer channels. The playback can later be resumed with pygame.mixer.unpause()
This will resume all active sound channels after they have been paused.
This will fade out the volume on all active channels over the time argument in milliseconds. After the sound is muted the playback will stop.
Sets the number of available channels for the mixer. The default value is 8. The value can be increased or decreased. If the value is decreased, sounds playing on the truncated channels are stopped.
Returns the number of currently active playback channels.
The mixer can reserve any number of channels that will not be automatically selected for playback by Sounds. If sounds are currently playing on the reserved channels they will not be stopped.
This allows the application to reserve a specific number of channels for important sounds that must not be dropped or have a guaranteed channel to play on.
This will find and return an inactive Channel object. If there are no inactive Channels this function will return None. If there are no inactive channels and the force argument is True, this will find the Channel with the longest running Sound and return it.
If the mixer has reserved channels from pygame.mixer.set_reserved() then those channels will not be returned here.
Returns True if the mixer is busy mixing any channels. If the mixer is idle then this return False.
Note
The linked and compile version numbers should be the same.
New in pygame 2.0.0.
Load a new sound buffer from a filename, a python file object or a readable buffer object. Limited resampling will be performed to help the sample match the initialize arguments for the mixer. A Unicode string can only be a file pathname. A Python 2.x string or a Python 3.x bytes object can be either a pathname or a buffer object. Use the 'file' or 'buffer' keywords to avoid ambiguity; otherwise Sound may guess wrong. If the array keyword is used, the object is expected to export a version 3, C level array interface or, for Python 2.6 or later, a new buffer interface (The object is checked for a buffer interface first.)
The Sound object represents actual sound sample data. Methods that change the state of the Sound object will the all instances of the Sound playback. A Sound object also exports an array interface, and, for Python 2.6 or later, a new buffer interface.
The Sound can be loaded from an OGG audio file or from an uncompressed WAV.
Note: The buffer will be copied internally, no data will be shared between it and the Sound object.
For now buffer and array support is consistent with sndarray.make_sound for Numeric arrays, in that sample sign and byte order are ignored. This will change, either by correctly handling sign and byte order, or by raising an exception when different. Also, source samples are truncated to fit the audio sample size. This will not change.
New in pygame 1.8: pygame.mixer.Sound(buffer)
New in pygame 1.9.2: pygame.mixer.Sound keyword arguments and array interface support
Begin playback of the Sound (i.e., on the computer's speakers) on an available Channel. This will forcibly select a Channel, so playback may cut off a currently playing sound if necessary.
The loops argument controls how many times the sample will be repeated after being played the first time. A value of 5 means that the sound will be played once, then repeated five times, and so is played a total of six times. The default value (zero) means the Sound is not repeated, and so is only played once. If loops is set to -1 the Sound will loop indefinitely (though you can still call stop() to stop it).
The maxtime argument can be used to stop playback after a given number of milliseconds.
The fade_ms argument will make the sound start playing at 0 volume and fade up to full volume over the time given. The sample may end before the fade-in is complete.
This returns the Channel object for the channel that was selected.
This will stop the playback of this Sound on any active Channels.
This will stop playback of the sound after fading it out over the time argument in milliseconds. The Sound will fade and stop on all actively playing channels.
This will set the playback volume (loudness) for this Sound. This will immediately affect the Sound if it is playing. It will also affect any future playback of this Sound.
volume in the range of 0.0 to 1.0 (inclusive)
Return a value from 0.0 to 1.0 representing the volume for this Sound.
Return the number of active channels this sound is playing on.
Return the length of this Sound in seconds.
Return a copy of the Sound object buffer as a bytes (for Python 3.x) or str (for Python 2.x) object.
New in pygame 1.9.2.
Return a Channel object for one of the current channels. The id must be a value from 0 to the value of pygame.mixer.get_num_channels().
The Channel object can be used to get fine control over the playback of Sounds. A channel can only playback a single Sound at time. Using channels is entirely optional since pygame can manage them by default.
This will begin playback of a Sound on a specific Channel. If the Channel is currently playing any other Sound it will be stopped.
The loops argument has the same meaning as in Sound.play(): it is the number of times to repeat the sound after the first time. If it is 3, the sound will be played 4 times (the first time, then three more). If loops is -1 then the playback will repeat indefinitely.
As in Sound.play(), the maxtime argument can be used to stop playback of the Sound after a given number of milliseconds.
As in Sound.play(), the fade_ms argument can be used fade in the sound.
Stop sound playback on a channel. After playback is stopped the channel becomes available for new Sounds to play on it.
Temporarily stop the playback of sound on a channel. It can be resumed at a later time with Channel.unpause()
Resume the playback on a paused channel.
Stop playback of a channel after fading out the sound over the given time argument in milliseconds.
Set the volume (loudness) of a playing sound. When a channel starts to play its volume value is reset. This only affects the current sound. The value argument is between 0.0 and 1.0.
If one argument is passed, it will be the volume of both speakers. If two arguments are passed and the mixer is in stereo mode, the first argument will be the volume of the left speaker and the second will be the volume of the right speaker. (If the second argument is None, the first argument will be the volume of both speakers.)
If the channel is playing a Sound on which set_volume() has also been called, both calls are taken into account. For example:
Return the volume of the channel for the current playing sound. This does not take into account stereo separation used by Channel.set_volume(). The Sound object also has its own volume which is mixed with the channel.
Returns True if the channel is actively mixing sound. If the channel is idle this returns False.
Return the actual Sound object currently playing on this channel. If the channel is idle None is returned.
When a Sound is queued on a Channel, it will begin playing immediately after the current Sound is finished. Each channel can only have a single Sound queued at a time. The queued Sound will only play if the current playback finished automatically. It is cleared on any other call to Channel.stop() or Channel.play().
If there is no sound actively playing on the Channel then the Sound will begin playing immediately.
If a Sound is already queued on this channel it will be returned. Once the queued sound begins playback it will no longer be on the queue.
When an endevent is set for a channel, it will send an event to the pygame queue every time a sound finishes playing on that channel (not just the first time). Use pygame.event.get() to retrieve the endevent once it's sent.
Note that if you called Sound.play(n) or Channel.play(sound,n), the end event is sent only once: after the sound has been played "n+1" times (see the documentation of Sound.play).
If Channel.stop() or Channel.play() is called while the sound was still playing, the event will be posted immediately.
The type argument will be the event id sent to the queue. This can be any valid event type, but a good choice would be a value between pygame.locals.USEREVENT and pygame.locals.NUMEVENTS. If no type argument is given then the Channel will stop sending endevents.
Returns the event type to be sent every time the Channel finishes playback of a Sound. If there is no endevent the function returns pygame.NOEVENT.


Return a Channel object for one of the current channels. The id must be a value from 0 to the value of pygame.mixer.get_num_channels().
The Channel object can be used to get fine control over the playback of Sounds. A channel can only playback a single Sound at time. Using channels is entirely optional since pygame can manage them by default.
This will begin playback of a Sound on a specific Channel. If the Channel is currently playing any other Sound it will be stopped.
The loops argument has the same meaning as in Sound.play(): it is the number of times to repeat the sound after the first time. If it is 3, the sound will be played 4 times (the first time, then three more). If loops is -1 then the playback will repeat indefinitely.
As in Sound.play(), the maxtime argument can be used to stop playback of the Sound after a given number of milliseconds.
As in Sound.play(), the fade_ms argument can be used fade in the sound.
Stop sound playback on a channel. After playback is stopped the channel becomes available for new Sounds to play on it.
Temporarily stop the playback of sound on a channel. It can be resumed at a later time with Channel.unpause()
Resume the playback on a paused channel.
Stop playback of a channel after fading out the sound over the given time argument in milliseconds.
Set the volume (loudness) of a playing sound. When a channel starts to play its volume value is reset. This only affects the current sound. The value argument is between 0.0 and 1.0.
If one argument is passed, it will be the volume of both speakers. If two arguments are passed and the mixer is in stereo mode, the first argument will be the volume of the left speaker and the second will be the volume of the right speaker. (If the second argument is None, the first argument will be the volume of both speakers.)
If the channel is playing a Sound on which set_volume() has also been called, both calls are taken into account. For example:
Return the volume of the channel for the current playing sound. This does not take into account stereo separation used by Channel.set_volume(). The Sound object also has its own volume which is mixed with the channel.
Returns True if the channel is actively mixing sound. If the channel is idle this returns False.
Return the actual Sound object currently playing on this channel. If the channel is idle None is returned.
When a Sound is queued on a Channel, it will begin playing immediately after the current Sound is finished. Each channel can only have a single Sound queued at a time. The queued Sound will only play if the current playback finished automatically. It is cleared on any other call to Channel.stop() or Channel.play().
If there is no sound actively playing on the Channel then the Sound will begin playing immediately.
If a Sound is already queued on this channel it will be returned. Once the queued sound begins playback it will no longer be on the queue.
When an endevent is set for a channel, it will send an event to the pygame queue every time a sound finishes playing on that channel (not just the first time). Use pygame.event.get() to retrieve the endevent once it's sent.
Note that if you called Sound.play(n) or Channel.play(sound,n), the end event is sent only once: after the sound has been played "n+1" times (see the documentation of Sound.play).
If Channel.stop() or Channel.play() is called while the sound was still playing, the event will be posted immediately.
The type argument will be the event id sent to the queue. This can be any valid event type, but a good choice would be a value between pygame.locals.USEREVENT and pygame.locals.NUMEVENTS. If no type argument is given then the Channel will stop sending endevents.
Returns the event type to be sent every time the Channel finishes playback of a Sound. If there is no endevent the function returns pygame.NOEVENT.


Stop playback of a channel after fading out the sound over the given time argument in milliseconds.


Returns True if the channel is actively mixing sound. If the channel is idle this returns False.


Returns the event type to be sent every time the Channel finishes playback of a Sound. If there is no endevent the function returns pygame.NOEVENT.


If a Sound is already queued on this channel it will be returned. Once the queued sound begins playback it will no longer be on the queue.


Return the actual Sound object currently playing on this channel. If the channel is idle None is returned.


Return the volume of the channel for the current playing sound. This does not take into account stereo separation used by Channel.set_volume(). The Sound object also has its own volume which is mixed with the channel.


Temporarily stop the playback of sound on a channel. It can be resumed at a later time with Channel.unpause()


This will begin playback of a Sound on a specific Channel. If the Channel is currently playing any other Sound it will be stopped.
The loops argument has the same meaning as in Sound.play(): it is the number of times to repeat the sound after the first time. If it is 3, the sound will be played 4 times (the first time, then three more). If loops is -1 then the playback will repeat indefinitely.
As in Sound.play(), the maxtime argument can be used to stop playback of the Sound after a given number of milliseconds.
As in Sound.play(), the fade_ms argument can be used fade in the sound.


When a Sound is queued on a Channel, it will begin playing immediately after the current Sound is finished. Each channel can only have a single Sound queued at a time. The queued Sound will only play if the current playback finished automatically. It is cleared on any other call to Channel.stop() or Channel.play().
If there is no sound actively playing on the Channel then the Sound will begin playing immediately.


When an endevent is set for a channel, it will send an event to the pygame queue every time a sound finishes playing on that channel (not just the first time). Use pygame.event.get() to retrieve the endevent once it's sent.
Note that if you called Sound.play(n) or Channel.play(sound,n), the end event is sent only once: after the sound has been played "n+1" times (see the documentation of Sound.play).
If Channel.stop() or Channel.play() is called while the sound was still playing, the event will be posted immediately.
The type argument will be the event id sent to the queue. This can be any valid event type, but a good choice would be a value between pygame.locals.USEREVENT and pygame.locals.NUMEVENTS. If no type argument is given then the Channel will stop sending endevents.


Set the volume (loudness) of a playing sound. When a channel starts to play its volume value is reset. This only affects the current sound. The value argument is between 0.0 and 1.0.
If one argument is passed, it will be the volume of both speakers. If two arguments are passed and the mixer is in stereo mode, the first argument will be the volume of the left speaker and the second will be the volume of the right speaker. (If the second argument is None, the first argument will be the volume of both speakers.)
If the channel is playing a Sound on which set_volume() has also been called, both calls are taken into account. For example:


Stop sound playback on a channel. After playback is stopped the channel becomes available for new Sounds to play on it.


Resume the playback on a paused channel.


This will fade out the volume on all active channels over the time argument in milliseconds. After the sound is muted the playback will stop.


This will find and return an inactive Channel object. If there are no inactive Channels this function will return None. If there are no inactive channels and the force argument is True, this will find the Channel with the longest running Sound and return it.
If the mixer has reserved channels from pygame.mixer.set_reserved() then those channels will not be returned here.


Returns True if the mixer is busy mixing any channels. If the mixer is idle then this return False.


If the mixer is initialized, this returns the playback arguments it is using. If the mixer has not been initialized this returns None.


Returns the number of currently active playback channels.


Note
The linked and compile version numbers should be the same.
New in pygame 2.0.0.


Initialize the mixer module for Sound loading and playback. The default arguments can be overridden to provide specific audio mixing. Keyword arguments are accepted. For backward compatibility where an argument is set zero the default value is used (possible changed by a pre_init call).
The size argument represents how many bits are used for each audio sample. If the value is negative then signed sample values will be used. Positive values mean unsigned audio samples will be used. An invalid value raises an exception.
The channels argument is used to specify whether to use mono or stereo. 1 for mono and 2 for stereo.
The buffer argument controls the number of internal samples used in the sound mixer. The default value should work for most cases. It can be lowered to reduce latency, but sound dropout may occur. It can be raised to larger values to ensure playback never skips, but it will impose latency on sound playback. The buffer size must be a power of two (if not it is rounded up to the next nearest power of 2).
Some platforms require the pygame.mixer module to be initialized after the display modules have initialized. The top level pygame.init() takes care of this automatically, but cannot pass any arguments to the mixer init. To solve this, mixer has a function pygame.mixer.pre_init() to set the proper defaults before the toplevel init is used.
When using allowedchanges=0 it will convert the samples at runtime to match what the hardware supports. For example a sound card may not support 16bit sound samples, so instead it will use 8bit samples internally. If AUDIO_ALLOW_FORMAT_CHANGE is supplied, then the requested format will change to the closest that SDL2 supports.
Apart from 0, allowedchanged accepts the following constants ORed together:
It is safe to call this more than once, but after the mixer is initialized you cannot change the playback arguments without first calling pygame.mixer.quit().
Changed in pygame 1.8: The default buffersize was changed from 1024 to 3072.
Changed in pygame 1.9.1: The default buffersize was changed from 3072 to 4096.
Changed in pygame 2.0.0: The default buffersize was changed from 4096 to 512. The default frequency changed to 44100 from 22050.
Changed in pygame 2.0.0: size can be 32 (32bit floats).
Changed in pygame 2.0.0: channels can also be 4 or 6.
New in pygame 2.0.0: allowedchanges argument added


The music module is closely tied to pygame.mixer. Use the music module to control the playback of music in the sound mixer.
The difference between the music playback and regular Sound playback is that the music is streamed, and never actually loaded all at once. The mixer system only supports a single music stream at once.
Be aware that MP3 support is limited. On some systems an unsupported format can crash the program, e.g. Debian Linux. Consider using OGG instead.
This will load a music filename/file object and prepare it for playback. If a music stream is already playing it will be stopped. This does not start the music playing.
This closes resources like files for any music that may be loaded.
New in pygame 2.0.0.
This will play the loaded music stream. If the music is already playing it will be restarted.
loops is an optional integer argument, which is 0 by default, it tells how many times to repeat the music. The music repeats indefinately if this argument is set to -1.
start is an optional float argument, which is 0.0 by default, which denotes the position in time, the music starts playing from. The starting position depends on the format of the music played. MP3 and OGG use the position as time in seconds. For mp3s the start time position selected may not be accurate as things like variable bit rate encoding and ID3 tags can throw off the timing calculations. For MOD music it is the pattern order number. Passing a start position will raise a NotImplementedError if the start position cannot be set.
fade_ms is an optional integer argument, which is 0 by default, makes the music start playing at 0 volume and fade up to full volume over the given time. The sample may end before the fade-in is complete.
Changed in pygame 2.0.0: Added optional fade_ms argument
Resets playback of the current music to the beginning.
Stops the music playback if it is currently playing. It Won't Unload the music.
Temporarily stop playback of the music stream. It can be resumed with the pygame.mixer.music.unpause() function.
This will resume the playback of a music stream after it has been paused.
Fade out and stop the currently playing music.
The time argument denotes the integer milliseconds for which the fading effect is generated.
Note, that this function blocks until the music has faded out. Calls to fadeout() and set_volume() will have no effect during this time. If an event was set using set_endevent() it will be called after the music has faded.
Set the volume of the music playback.
The volume argument is a float between 0.0 and 1.0 that sets volume. When new music is loaded the volume is reset to full volume.
Returns the current volume for the mixer. The value will be between 0.0 and 1.0.
Returns True when the music stream is actively playing. When the music is idle this returns False. In pygame 2.0.1 and above this function returns False when the music is paused. In pygame 1 it returns True when the music is paused.
Changed in pygame 2.0.1: Returns False when music paused.
This sets the position in the music file where playback will start. The meaning of "pos", a float (or a number that can be converted to a float), depends on the music format.
For MOD files, pos is the integer pattern number in the module. For OGG it is the absolute position, in seconds, from the beginning of the sound. For MP3 files, it is the relative position, in seconds, from the current position. For absolute positioning in an MP3 file, first call rewind().
Other file formats are unsupported. Newer versions of SDL_mixer have better positioning support than earlier ones. An SDLError is raised if a particular format does not support positioning.
Function set_pos() calls underlining SDL_mixer function Mix_SetMusicPosition.
New in pygame 1.9.2.
This gets the number of milliseconds that the music has been playing for. The returned time only represents how long the music has been playing; it does not take into account any starting position offsets.
This will load a sound file and queue it. A queued sound file will begin as soon as the current sound naturally ends. Only one sound can be queued at a time. Queuing a new sound while another sound is queued will result in the new sound becoming the queued sound. Also, if the current sound is ever stopped or changed, the queued sound will be lost.
The following example will play music by Bach six times, then play music by Mozart once:
This causes pygame to signal (by means of the event queue) when the music is done playing. The argument determines the type of event that will be queued.
The event will be queued every time the music finishes, not just the first time. To stop the event from being queued, call this method with no argument.
Returns the event type to be sent every time the music finishes playback. If there is no endevent the function returns pygame.NOEVENT.


Fade out and stop the currently playing music.
The time argument denotes the integer milliseconds for which the fading effect is generated.
Note, that this function blocks until the music has faded out. Calls to fadeout() and set_volume() will have no effect during this time. If an event was set using set_endevent() it will be called after the music has faded.


Returns True when the music stream is actively playing. When the music is idle this returns False. In pygame 2.0.1 and above this function returns False when the music is paused. In pygame 1 it returns True when the music is paused.
Changed in pygame 2.0.1: Returns False when music paused.


Returns the event type to be sent every time the music finishes playback. If there is no endevent the function returns pygame.NOEVENT.


This gets the number of milliseconds that the music has been playing for. The returned time only represents how long the music has been playing; it does not take into account any starting position offsets.


Returns the current volume for the mixer. The value will be between 0.0 and 1.0.


This will load a music filename/file object and prepare it for playback. If a music stream is already playing it will be stopped. This does not start the music playing.


Temporarily stop playback of the music stream. It can be resumed with the pygame.mixer.music.unpause() function.


This will play the loaded music stream. If the music is already playing it will be restarted.
loops is an optional integer argument, which is 0 by default, it tells how many times to repeat the music. The music repeats indefinately if this argument is set to -1.
start is an optional float argument, which is 0.0 by default, which denotes the position in time, the music starts playing from. The starting position depends on the format of the music played. MP3 and OGG use the position as time in seconds. For mp3s the start time position selected may not be accurate as things like variable bit rate encoding and ID3 tags can throw off the timing calculations. For MOD music it is the pattern order number. Passing a start position will raise a NotImplementedError if the start position cannot be set.
fade_ms is an optional integer argument, which is 0 by default, makes the music start playing at 0 volume and fade up to full volume over the given time. The sample may end before the fade-in is complete.
Changed in pygame 2.0.0: Added optional fade_ms argument


This will load a sound file and queue it. A queued sound file will begin as soon as the current sound naturally ends. Only one sound can be queued at a time. Queuing a new sound while another sound is queued will result in the new sound becoming the queued sound. Also, if the current sound is ever stopped or changed, the queued sound will be lost.
The following example will play music by Bach six times, then play music by Mozart once:


Resets playback of the current music to the beginning.


This causes pygame to signal (by means of the event queue) when the music is done playing. The argument determines the type of event that will be queued.
The event will be queued every time the music finishes, not just the first time. To stop the event from being queued, call this method with no argument.


This sets the position in the music file where playback will start. The meaning of "pos", a float (or a number that can be converted to a float), depends on the music format.
For MOD files, pos is the integer pattern number in the module. For OGG it is the absolute position, in seconds, from the beginning of the sound. For MP3 files, it is the relative position, in seconds, from the current position. For absolute positioning in an MP3 file, first call rewind().
Other file formats are unsupported. Newer versions of SDL_mixer have better positioning support than earlier ones. An SDLError is raised if a particular format does not support positioning.
Function set_pos() calls underlining SDL_mixer function Mix_SetMusicPosition.
New in pygame 1.9.2.


Set the volume of the music playback.
The volume argument is a float between 0.0 and 1.0 that sets volume. When new music is loaded the volume is reset to full volume.


Stops the music playback if it is currently playing. It Won't Unload the music.


This closes resources like files for any music that may be loaded.
New in pygame 2.0.0.


This will resume the playback of a music stream after it has been paused.


This will temporarily stop all playback on the active mixer channels. The playback can later be resumed with pygame.mixer.unpause()