def test_init__keyword_args(self):
# Fails on a Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
## configs = ( {'frequency' : f, 'size' : s, 'channels': c }
## for f in FREQUENCIES
## for s in SIZES
## for c in CHANNELS )
#### configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]
configs = [{'frequency' : 22050, 'size' : -16, 'channels' : 2}]
for kw_conf in configs:
mixer.init(**kw_conf)
mixer_conf = mixer.get_init()
self.assertEquals(
# Not all "sizes" are supported on all systems.
(mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
(kw_conf['frequency'],
abs(kw_conf['size']),
kw_conf['channels'])
)
mixer.quit()
python类mixer()的实例源码
def todo_test_pre_init__keyword_args(self):
# Fails on Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
## configs = ( {'frequency' : f, 'size' : s, 'channels': c }
## for f in FREQUENCIES
## for s in SIZES
## for c in CHANNELS )
configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]
for kw_conf in configs:
mixer.pre_init(**kw_conf)
mixer.init()
mixer_conf = mixer.get_init()
self.assertEquals(
# Not all "sizes" are supported on all systems.
(mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
(kw_conf['frequency'],
abs(kw_conf['size']),
kw_conf['channels'])
)
mixer.quit()
def _test_array_argument(self, format, a, test_pass):
from numpy import array, all as all_
try:
snd = mixer.Sound(array=a)
except ValueError:
if not test_pass:
return
self.fail("Raised ValueError: Format %i, dtype %s" %
(format, a.dtype))
if not test_pass:
self.fail("Did not raise ValueError: Format %i, dtype %s" %
(format, a.dtype))
a2 = array(snd)
a3 = a.astype(a2.dtype)
lshift = abs(format) - 8 * a.itemsize
if lshift >= 0:
# This is asymmetric with respect to downcasting.
a3 <<= lshift
self.assert_(all_(a2 == a3),
"Format %i, dtype %s" % (format, a.dtype))
def test_array_interface(self):
mixer.init(22050, -16, 1)
try:
snd = mixer.Sound(as_bytes('\x00\x7f') * 20)
d = snd.__array_interface__
self.assertTrue(isinstance(d, dict))
if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
typestr = '<i2'
else:
typestr = '>i2'
self.assertEqual(d['typestr'], typestr)
self.assertEqual(d['shape'], (20,))
self.assertEqual(d['strides'], (2,))
self.assertEqual(d['data'], (snd._samples_address, False))
finally:
mixer.quit()
def test_get_raw(self):
from ctypes import pythonapi, c_void_p, py_object
try:
Bytes_FromString = pythonapi.PyBytes_FromString
except:
Bytes_FromString = pythonapi.PyString_FromString
Bytes_FromString.restype = c_void_p
Bytes_FromString.argtypes = [py_object]
mixer.init()
try:
samples = as_bytes('abcdefgh') # keep byte size a multiple of 4
snd = mixer.Sound(buffer=samples)
raw = snd.get_raw()
self.assertTrue(isinstance(raw, bytes_))
self.assertNotEqual(snd._samples_address, Bytes_FromString(samples))
self.assertEqual(raw, samples)
finally:
mixer.quit()
def todo_test_find_channel(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.find_channel:
# pygame.mixer.find_channel(force=False): return Channel
# find an unused channel
#
# 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.
#
self.fail()
def todo_test_pre_init(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.pre_init:
# pygame.mixer.pre_init(frequency=0, size=0, channels=0,
# buffersize=0): return None
#
# preset the mixer init arguments
#
# Any nonzero arguments change the default values used when the real
# pygame.mixer.init() is called. The best way to set custom mixer
# playback values is to call pygame.mixer.pre_init() before calling
# the top level pygame.init().
#
self.fail()
def todo_test_set_reserved(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.set_reserved:
# pygame.mixer.set_reserved(count): return None
# reserve channels from being automatically used
#
# 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.
#
self.fail()
def todo_test_Channel(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel:
# pygame.mixer.Channel(id): return Channel
# Create a Channel object for controlling playback
#
# 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.
#
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.play:
# Channel.play(Sound, loops=0, maxtime=0, fade_ms=0): return None
# play a Sound on a specific Channel
#
# 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.
self.fail()
def todo_test_queue(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.queue:
# Channel.queue(Sound): return None
# queue a Sound object to follow the current
#
# 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.
#
self.fail()
def playmusic2(soundfile):
"""Stream music with mixer.music module using the event module to wait
until the playback has finished.
This method doesn't use a busy/poll loop, but has the disadvantage that
you neet to initialize the video module to use the event module.
Also, interrupting the playback with Ctrl-C does not work :-(
Change the call to 'playmusic' in the 'main' function to 'playmusic2'
to use this method.
"""
pygame.init()
pygame.mixer.music.load(soundfile)
pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
pygame.event.set_allowed(pygame.constants.USEREVENT)
pygame.mixer.music.play()
pygame.event.wait()
def play(name, volume=1.0, pos=-1):
prefvolume = [0, 0.6, 1.0][game.volume]
volume *= prefvolume
if not volume:
return
sound = fetch(name)
if sound:
chan = sound.play()
if not chan:
chan = pygame.mixer.find_channel(1)
chan.play(sound)
if chan:
if pos == -1:
percent = 0.5
else:
percent = (pos / 700.0)
inv = 1.0 - percent
chan.set_volume(inv*volume, percent*volume)
def make_sound (array):
"""pygame._numpysndarray.make_sound(array): return Sound
Convert an array into a Sound object.
Create a new playable Sound object from an array. The mixer module
must be initialized and the array format must be similar to the mixer
audio format.
"""
# Info is a (freq, format, stereo) tuple
info = pygame.mixer.get_init ()
if not info:
raise pygame.error("Mixer not initialized")
channels = info[2]
shape = array.shape
if channels == 1:
if len (shape) != 1:
raise ValueError("Array must be 1-dimensional for mono mixer")
else:
if len (shape) != 2:
raise ValueError("Array must be 2-dimensional for stereo mixer")
elif shape[1] != channels:
raise ValueError("Array depth must match number of mixer channels")
return mixer.Sound (array)
def load_sound(file):
if not pygame.mixer: return dummysound()
file = os.path.join('data', file)
try:
sound = pygame.mixer.Sound(file)
return sound
except pygame.error:
print 'Warning, unable to load,', file
return dummysound()
# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it's current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard
def load_sound(file):
if not pygame.mixer: return dummysound()
file = os.path.join(main_dir, 'data', file)
try:
sound = pygame.mixer.Sound(file)
return sound
except pygame.error:
print ('Warning, unable to load, %s' % file)
return dummysound()
# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it's current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard
def test_init__keyword_args(self):
# Fails on a Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
## configs = ( {'frequency' : f, 'size' : s, 'channels': c }
## for f in FREQUENCIES
## for s in SIZES
## for c in CHANNELS )
#### configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]
configs = [{'frequency' : 22050, 'size' : -16, 'channels' : 2}]
for kw_conf in configs:
mixer.init(**kw_conf)
mixer_conf = mixer.get_init()
self.assertEquals(
# Not all "sizes" are supported on all systems.
(mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
(kw_conf['frequency'],
abs(kw_conf['size']),
kw_conf['channels'])
)
mixer.quit()
def todo_test_pre_init__keyword_args(self):
# Fails on Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
## configs = ( {'frequency' : f, 'size' : s, 'channels': c }
## for f in FREQUENCIES
## for s in SIZES
## for c in CHANNELS )
configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]
for kw_conf in configs:
mixer.pre_init(**kw_conf)
mixer.init()
mixer_conf = mixer.get_init()
self.assertEquals(
# Not all "sizes" are supported on all systems.
(mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
(kw_conf['frequency'],
abs(kw_conf['size']),
kw_conf['channels'])
)
mixer.quit()
def todo_test_find_channel(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.find_channel:
# pygame.mixer.find_channel(force=False): return Channel
# find an unused channel
#
# 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.
#
self.fail()
def todo_test_pre_init(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.pre_init:
# pygame.mixer.pre_init(frequency=0, size=0, channels=0,
# buffersize=0): return None
#
# preset the mixer init arguments
#
# Any nonzero arguments change the default values used when the real
# pygame.mixer.init() is called. The best way to set custom mixer
# playback values is to call pygame.mixer.pre_init() before calling
# the top level pygame.init().
#
self.fail()
def todo_test_Channel(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel:
# pygame.mixer.Channel(id): return Channel
# Create a Channel object for controlling playback
#
# 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.
#
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.play:
# Channel.play(Sound, loops=0, maxtime=0, fade_ms=0): return None
# play a Sound on a specific Channel
#
# 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.
self.fail()
def loadSound(self, name):
'''Load a sound. Set this function to a variable then call variable.play()'''
try:
pygame.mixer.get_init()
except:
pass
class NoneSound:
def play(self): pass
if not pygame.mixer:
return NoneSound()
fullname = os.path.join(scriptdir, name)
try:
sound = pygame.mixer.Sound(fullname)
except pygame.error as e:
print ('Cannot load sound: %s' % fullname)
raise e
return sound
def array (sound):
"""pygame._numpysndarray.array(Sound): return array
Copy Sound samples into an array.
Creates a new array for the sound data and copies the samples. The
array will always be in the format returned from
pygame.mixer.get_init().
"""
return numpy.array (sound, copy=True)
def samples (sound):
"""pygame._numpysndarray.samples(Sound): return array
Reference Sound samples into an array.
Creates a new array that directly references the samples in a Sound
object. Modifying the array will change the Sound. The array will
always be in the format returned from pygame.mixer.get_init().
"""
return numpy.array (sound, copy=False)
def make_sound (array):
"""pygame._numpysndarray.make_sound(array): return Sound
Convert an array into a Sound object.
Create a new playable Sound object from an array. The mixer module
must be initialized and the array format must be similar to the mixer
audio format.
"""
return mixer.Sound (array=array)
def load_sound(file):
if not pygame.mixer: return dummysound()
file = os.path.join('data', file)
try:
sound = pygame.mixer.Sound(file)
return sound
except pygame.error:
print ('Warning, unable to load,', file)
return dummysound()
# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it's current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard
def load_sound(name):
class NoneSound:
def play(self): pass
if not pygame.mixer or not pygame.mixer.get_init():
return NoneSound()
fullname = os.path.join(data_dir, name)
try:
sound = pygame.mixer.Sound(fullname)
except pygame.error:
print ('Cannot load sound: %s' % fullname)
raise SystemExit(str(geterror()))
return sound
#classes for our game objects
def sound_from_pos(sound, start_pos, samples_per_second = None, inplace = 1):
""" returns a sound which begins at the start_pos.
start_pos - in seconds from the begining.
samples_per_second -
"""
# see if we want to reuse the sound data or not.
if inplace:
a1 = pygame.sndarray.samples(sound)
else:
a1 = pygame.sndarray.array(sound)
# see if samples per second has been given. If not, query the mixer.
# eg. it might be set to 22050
if samples_per_second is None:
samples_per_second = pygame.mixer.get_init()[0]
# figure out the start position in terms of samples.
start_pos_in_samples = int(start_pos * samples_per_second)
# cut the begining off the sound at the start position.
a2 = a1[start_pos_in_samples:]
# make the Sound instance from the array.
sound2 = pygame.sndarray.make_sound(a2)
return sound2
def todo_test_pre_init__zero_values(self):
# Ensure that argument values of 0 are replaced with
# default values. No way to check buffer size though.
mixer.pre_init(44100, -8, 1) # Non default values
mixer.pre_init(0, 0, 0) # Should reset to default values
mixer.init()
try:
self.failUnlessEqual(mixer.get_init(), (22050, -16, 2))
finally:
mixer.quit()