Package speakeasy :: Module sound_player :: Class SoundPlayer
[hide private]
[frames] | no frames]

Class SoundPlayer

source code

object --+
         |
        SoundPlayer

Plays up to NUM_SIMULTANEOUS_SOUNDS .wav/.ogg files simultaneously. Allows pause/unpause on any of these sounds. (.ogg untested)

Theory of operation: The class uses the pygame module. This module involves Sound instances and Channel instances. A Sound is created from a .wav or .ogg file, and can play on one or more Channel instances.

All channels can simultaneously play, one Sound per channel. The number of channels can be set via the module-global constant NUM_SIMULTANEOUS_SOUNDS. Default is 8. Channels and Sounds are managed by pygame.mixer.

This class uses parameter polymorphism to unify all these concepts as much as possible. The only public methods are <code>play(), stop(), pause(), unpause(),set_volume(), get_volume()</code>. Each of these methods takes either the path to a sound file, a Sound instances, or a Channel instance. The SoundPlayer takes care of creating Sound instances by loading them from files, caching sounds, and tracking which Sounds are playing on which Channel at any time. Callers of these methods need to deal only with the sound file paths. These paths, when passed to, say, the pause() method, will do the right thing; Sound instances are cached, so they will not be loaded repeatedly.

Note that this wonderful collapsing of complex underlying pygame concepts comes at a price in code ugliness. Since Python does not have parameter based polymorphism, methods must figure out incoming parameter types via duck typing methods: Treat the parameters as some type and see whether an error occurs. Terrible, but the 'pythonic' way.

As background: The pygame API provides methods three entities: Mixer, Channel, and Sound. The main methods are:

  1. Mixer:
  2. Channel:
  3. Sound:
Instance Methods [hide private]
 
__init__(self)
x.__init__(...) initializes x; see help(type(x)) for signature
source code
 
play(self, whatToPlay, blockTillDone=False, volume=None)
Play a file, or an already loaded Sound instance.
source code
 
stop(self, whatToStop=None)
Stop either all currently playing sounds, or a particular sound.
source code
 
pause(self, whatToPause=None)
Pause either all currently playing sounds, or a particular sound.
source code
 
unpause(self, whatToUnPause=None)
Unpause either all currently playing sounds, or a particular sound.
source code
 
setSoundVolume(self, volume, whatToSetVolFor=None)
Set sound volume for a particular sound or channel.
source code
 
getSoundVolume(self, whatToGetVolFor=None)
Get sound volume for a particular sound or channel.
source code
boolean
formatSupported(self, fileExtension)
Checks whether the given file extension implies a supported sound format.
source code
 
numChannels(self)
Number of sounds to play simultaneously.
source code
 
loadSound(self, filename)
Create a Sound instance from the given file.
source code
 
checkCacheStatus(self)
Ensures that number of cached sounds does not exceed NUM_OF_CACHED_SOUNDS.
source code
 
unloadSound(self, sound)
Remove Sound instance from cache and all other references.
source code
(Sound, Channel)
playFile(self, filename, volume=None)
Private Method! Called by play(); Given a filename, load it into a Sound instance, if it is not already cached.
source code
 
stopFile(self, filename)
Private Method! Called by stop(); Stops currently playing sound from the given filename.
source code
 
pauseFile(self, filename)
Private Method! Called by pause(); Pauses currently playing sound from the given filename.
source code
Sound
unpauseFile(self, filename)
Unpauses currently paused sound from the given filename.
source code
{Sound | NoneType}
getSoundFromFileName(self, filename)
Given a sound file path name, return the corresponding Sound instance, if the file was loaded.
source code
 
getSoundFromChannel(self, channel)
Return Sound instance that is currently playing on the given Channel instance.
source code
{[Channel] | NoneType}
getChannelsFromSound(self, sound)
Return all channels on which the given Sound instance is currently playing.
source code
 
addSoundToChannelBinding(self, sound, channel)
Register that a Sound is beginning to play on a given Channel.
source code
 
cleanupSoundChannelBindings(self)
Runs through the sound-to-channel bindings and removes the entries of channels that are done playing.
source code
 
waitForSoundDone(self, sound)
Block until sound is done playing on all channels on which it is currently playing.
source code

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Class Variables [hide private]
  singletonInstanceRunning = False
  supportedFormats = ['ogg', 'wav']
Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self)
(Constructor)

source code 

x.__init__(...) initializes x; see help(type(x)) for signature

Overrides: object.__init__
(inherited documentation)

play(self, whatToPlay, blockTillDone=False, volume=None)

source code 

Play a file, or an already loaded Sound instance. Offers choice of blocking return until the sound is finished, or returning immediately.

Parameters:
  • whatToPlay ({string | Sound}) - Full path to .wav or .ogg file, or Sound instance.
  • blockTillDone (boolean) - True to delay return until sound is done playing.
  • volume (float) - Volume to play at. Float between 0.0 and 1.0. None: use current volume.
Returns:
The sound instance.
Raises:
  • IOError - if given sound file path does not exist, or some other playback error occurred.
  • ValueError - if given volume is not between 0.0 and 1.0
  • TypeError - if whatToPlay is not a filename (string), or Sound instance.

stop(self, whatToStop=None)

source code 

Stop either all currently playing sounds, or a particular sound. The sound to stop (parameter whatToStop) may be specified as a the full-path filename of the respective .wav/.ogg file, as a Sound instance, or as a Channel instance.

Parameters:
  • whatToStop ({NoneType | string | Sound | Channel}) - If None, top all currently playing sounds. If any a Sound instance, stop this sound on all channels on which it might currently be playing. If a Channel instance, stop only whatever is currently playing on this channel.

pause(self, whatToPause=None)

source code 

Pause either all currently playing sounds, or a particular sound. The sound to pause (parameter whatToStop) may be specified as a the full-path filename of the respective .wav/.ogg file, as a Sound instance, or as a Channel instance.

Parameters:
  • whatToPause ({NoneType | string | Sound | Channel | [Channel]}) - If None, top all currently playing sounds. If any a Sound instance, pause this sound on all channels on which it might currently be playing. If a Channel or array of channel instances, pause whatever is currently playing on the given channel(s).
Raises:
  • TypeError - if whatToPause is of illegal type.

unpause(self, whatToUnPause=None)

source code 

Unpause either all currently playing sounds, or a particular sound. The sound to unpause (parameter whatToStop) may be specified as a the full-path filename of the respective .wav/.ogg file, as a Sound instance, or as a Channel instance.

Parameters:
  • whatToUnPause ({NoneType | string | Sound | Channel}) - If None, unpause all currently playing sounds. If whatToUnPause is a Sound instance, pause this sound on all channels on which it might currently be playing. If whatToUnPause is a Channel or array of channel instances, pause whatever is currently playing on the given channel(s).

setSoundVolume(self, volume, whatToSetVolFor=None)

source code 

Set sound volume for a particular sound or channel. The entity for which to set the volume (i.e. whatToSetVolFor) may be the full-path filename of a .wav/.ogg file, a Sound instance, or a Channel instance. Here is the interaction between settings of Sound vs. Channel volume:

  • sound.set_volume(0.9) # Now plays at 90% of full volume.
  • sound.set_volume(0.6) # Now plays at 60% (previous value replaced).
  • channel.set_volume(0.5) # Now plays at 30% (0.6 * 0.5).

Passing in a filename will load the file, and set the volume of the corresponding Sound.

Parameters:
  • volume (float) - Value between 0.0 and 1.0.
  • whatToSetVolFor ({NoneType | string | Sound | Channel}) - The soundfile, Sound, or Channel instance whose volume to set. If None, sets volume for all sounds. (This setting is overridden by volume settings provided in calls to the play() method.
Raises:
  • OSError - if given filename that does not exist.

getSoundVolume(self, whatToGetVolFor=None)

source code 

Get sound volume for a particular sound or channel. The entity for which to get the volume for (i.e. whatToSetVolFor) may be the full-path filename of a .wav/.ogg file, a Sound instance, or a Channel instance. Here is the interaction between settings of Sound vs. Channel volume:

  • sound.set_volume(0.9) # Now plays at 90% of full volume.
  • sound.set_volume(0.6) # Now plays at 60% (previous value replaced).
  • channel.set_volume(0.5) # Now plays at 30% (0.6 * 0.5).

Passing in a filename will load the file, and get the volume of the corresponding Sound.

Parameters:
  • whatToGetVolFor ({NoneType | string | Sound | Channel}) - The soundfile, Sound, or Channel instance whose volume to get. If None, return global value setting
Raises:
  • OSError - if given filename that does not exist.

formatSupported(self, fileExtension)

source code 

Checks whether the given file extension implies a supported sound format.

Parameters:
  • fileExtension (string) - file extension with or without leading period. Example: ".ogg"
Returns: boolean
True if the format is supported, else False.
Raises:
  • ValueError - if fileExtension is anything other than a string with length > 0.

numChannels(self)

source code 

Number of sounds to play simultaneously. Controlled by module variable NUM_SIMULTANEOUS_SOUNDS.

loadSound(self, filename)

source code 

Create a Sound instance from the given file. Cache the sound, and initialize the LRU cache last-used time.

Parameters:
  • filename (string) - Full path to sound file (.wav/.ogg)
Raises:
  • IOError - if file does not exist.

checkCacheStatus(self)

source code 

Ensures that number of cached sounds does not exceed NUM_OF_CACHED_SOUNDS. If it does, half the cache is emptied in order of least-recently-used first.

unloadSound(self, sound)

source code 

Remove Sound instance from cache and all other references.

Parameters:
  • sound (Sound) - Sound instance to remove

playFile(self, filename, volume=None)

source code 

Private Method! Called by play(); Given a filename, load it into a Sound instance, if it is not already cached. Set the volume, if given, and play. It is assumed that the volume value, if given, has been verified by the caller to be between 0.0 and 1.0.

Parameters:
  • filename (string) - Name of sound file to play
  • volume (float) - Volume to play at: 0.0 to 1.0
Returns: (Sound, Channel)
Sound and channel instances
Raises:
  • OSError - if file does not exist.

stopFile(self, filename)

source code 

Private Method! Called by stop(); Stops currently playing sound from the given filename. Does nothing if this file is not currently playing.

Parameters:
  • filename (string) - Filename from which the Sound instance to be stopped was created.
Raises:
  • TypeError - filename is not a string.

pauseFile(self, filename)

source code 

Private Method! Called by pause(); Pauses currently playing sound from the given filename. Does nothing if this file is not currently playing.

Parameters:
  • filename (string) - Filename from which the Sound instance to be paused was created.
Returns:
Sound instance
Raises:
  • TypeError - filename is not a string.

unpauseFile(self, filename)

source code 

Unpauses currently paused sound from the given filename. Does nothing if this file is not currently playing or paused.

Parameters:
  • filename (string) - Filename from which the Sound instance to be unpaused was created.
Returns: Sound
Sound instance
Raises:
  • TypeError - filename is not a string.

getSoundFromFileName(self, filename)

source code 

Given a sound file path name, return the corresponding Sound instance, if the file was loaded. Else return None.

Parameters:
  • filename (string) - Filename from which the Sound instance was created.
Returns: {Sound | NoneType}
Sound instance created from the given file. None if file not yet loaded.

getSoundFromChannel(self, channel)

source code 

Return Sound instance that is currently playing on the given Channel instance. None if channel is inactive.

Parameters:
  • channel (Channel) - Channel to be investigated.

getChannelsFromSound(self, sound)

source code 

Return all channels on which the given Sound instance is currently playing.

Parameters:
  • sound (Sound) - Sound instance to be hunted down.
Returns: {[Channel] | NoneType}
Array of Channel instances, or None, if Sound is not currently playing on any channel.

addSoundToChannelBinding(self, sound, channel)

source code 

Register that a Sound is beginning to play on a given Channel.

Parameters:
  • sound (Sound) - Sound to bind
  • channel (Channel) - Channel to bind to

waitForSoundDone(self, sound)

source code 

Block until sound is done playing on all channels on which it is currently playing.

Parameters:
  • sound (Sound) - Sound to monitor