def __init__(self, value="C", secs=0.5, octave=4, sampleRate=44100, bits=16, name='', autoLog=True, loops=0, stereo=True): """ """ self.name = name # only needed for autoLogging self.autoLog = autoLog if stereo == True: stereoChans = 2 else: stereoChans = 0 if bits == 16: # for pygame bits are signed for 16bit, signified by the minus bits = -16 # check initialisation if not mixer.get_init(): pygame.mixer.init(sampleRate, bits, stereoChans, 3072) inits = mixer.get_init() if inits is None: init() inits = mixer.get_init() self.sampleRate, self.format, self.isStereo = inits # try to create sound self._snd = None # distinguish the loops requested from loops actual because of # infinite tones (which have many loops but none requested) # -1 for infinite or a number of loops self.requestedLoops = self.loops = int(loops) self.setSound(value=value, secs=secs, octave=octave)
def build_samples(self): period = int(round(get_init()[0] / self.frequency)) samples = array("h", [0] * period) amplitude = 2 ** (abs(get_init()[1]) - 1) - 1 for time in xrange(period): if time < period / 2: samples[time] = amplitude else: samples[time] = -amplitude return samples
def build_samples(frequency): """Build an array of the wave for this frequency""" # Hz is cycles per second # period = 44100 Hz / 440 Hz = 100 samples per cycle # Given samples and cycles per second get the period of each cycle period = int(round(mixer.get_init()[0] / frequency)) # Make one full wave's period samples = array("h", [0] * period) # Fill with a square wave amplitude = 2 ** (abs(mixer.get_init()[1]) - 1) - 1 for time in xrange(period): if time < period / 2: samples[time] = amplitude else: samples[time] = -amplitude return samples
def initPygame(rate=22050, bits=16, stereo=True, buffer=1024): """If you need a specific format for sounds you need to run this init function. Run this *before creating your visual.Window*. The format cannot be changed once initialised or once a Window has been created. If a Sound object is created before this function is run it will be executed with default format (signed 16bit stereo at 22KHz). For more details see pygame help page for the mixer. """ global Sound, audioDriver Sound = SoundPygame audioDriver='n/a' if stereo==True: stereoChans=2 else: stereoChans=0 if bits==16: bits=-16 #for pygame bits are signed for 16bit, signified by the minus mixer.init(rate, bits, stereoChans, buffer) #defaults: 22050Hz, 16bit, stereo, sndarray.use_arraytype("numpy") setRate, setBits, setStereo = mixer.get_init() if setRate!=rate: logging.warn('Requested sound sample rate was not poossible') if setBits!=bits: logging.warn('Requested sound depth (bits) was not possible') if setStereo!=2 and stereo==True: logging.warn('Requested stereo setting was not possible')
def playSound(nom): """Joue un son une fois""" global volumeGlobal, volumeSons if not mixer.get_init() : mixer.init() son = mixer.Sound('Sons/' + nom + '.ogg') son.set_volume(float(volumeGlobal)*float(volumeSound)/10000) son.play()
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 _array_samples(sound, raw): # Info is a (freq, format, stereo) tuple info = mixer.get_init () if not info: raise pygame.error("Mixer not initialized") fmtbytes = (abs (info[1]) & 0xff) >> 3 channels = info[2] if raw: data = sound.get_buffer ().raw else: data = sound.get_buffer () shape = (len (data) // fmtbytes, ) if channels > 1: shape = (shape[0] // channels, channels) # mixer.init () does not support different formats from the ones below, # so MSB/LSB stuff is silently ignored. typecode = { 8 : numpy.uint8, # AUDIO_U8 16 : numpy.uint16, # AUDIO_U16 / AUDIO_U16SYS -8 : numpy.int8, # AUDIO_S8 -16 : numpy.int16 # AUDUI_S16 / AUDIO_S16SYS }[info[1]] array = numpy.fromstring (data, typecode) array.shape = shape return array
def stop_channel(channel): """ Stop sound on a channel. """ if mixer.get_init(): mixer.Channel(channel).stop() # play short silence to avoid blocking the channel - it won't play on queue() silence = pygame.sndarray.make_sound(numpy.zeros(1, numpy.int16)) mixer.Channel(channel).play(silence)
def test_get_init__returns_exact_values_used_for_init(self): return # fix in 1.9 - I think it's a SDL_mixer bug. # TODO: When this bug is fixed, testing through every combination # will be too slow so adjust as necessary, at the moment it # breaks the loop after first failure configs = [] for f in FREQUENCIES: for s in SIZES: for c in CHANNELS: configs.append ((f,s,c)) print (configs) for init_conf in configs: print (init_conf) f,s,c = init_conf if (f,s) == (22050,16):continue mixer.init(f,s,c) mixer_conf = mixer.get_init() import time time.sleep(0.1) mixer.quit() time.sleep(0.1) if init_conf != mixer_conf: continue self.assertEquals(init_conf, mixer_conf)
def __init__(self, display_w, display_h): pygame.init() mixer.init() font.init() # check if the mixer was successfully initialized if mixer.get_init() is None: print("Failed to initialize the audio mixer module.") if font.get_init() is None: print("Failed to initialize the font module.") self.fps = 120 self.world = None self.gui = Gui(self) # Create screen display with 32 bits per pixel, no flags set self.display = pygame.display.set_mode((display_w, display_h), pygame.HWSURFACE, 32) self.delta_time = 0.0 self.debug = False self.paused = False self.print_fps = False self.worlds = list() self.game = None
def __init__(self,value="C",secs=0.5,octave=4, sampleRate=44100, bits=16): """ """ #check initialisation if not mixer.get_init(): pygame.mixer.init(22050, -16, 2, 3072) inits = mixer.get_init() if inits is None: init() inits = mixer.get_init() self.sampleRate, self.format, self.isStereo = inits #try to create sound self._snd=None self.setSound(value=value, secs=secs, octave=octave)
def play(self, name, queue_sounds=False, play_next_queued_sound=False, loop_forever=False, callback=None): if not mixer.get_init(): print "Mixer not initialized! Cannot play sound." #channel = mixer.find_channel() #channel.play(self.sounds[id]) sound_item = self.sounds[name] if queue_sounds: if mixer.music.get_busy(): mixer.music.queue(sound_item.path) print "Queued sound: " + name if play_next_queued_sound: mixer.music.play() if callback: print "Channel playback end callback defined" self.channel_playback_ended_listener(mixer.music, callback) else: mixer.music.load(sound_item.path) if loop_forever: mixer.music.play(-1) else: mixer.music.play() print "Playing sound: " + name if callback: print "Channel playback end callback defined" self.channel_playback_ended_listener(mixer.music, callback) else: if loop_forever: loops = -1 else: loops = 0 if sound_item.delay == sound_item.delay_min == sound_item.delay_max == 0: sound_item.sound.play(loops) elif sound_item.delay > 0: #pygame.time.wait(sound_item.delay) self.play_after_delay(sound_item.sound, sound_item.delay, loops) elif sound_item.delay_min == sound_item.delay_max: self.play_after_delay(sound_item.sound, sound_item.delay_min, loops) #pygame.time.wait(sound_item.delay_min) elif sound_item.delay_min > 0 and sound_item.delay_max > 0: rand = random.randrange(sound_item.delay_min, sound_item.delay_max, 250) #pygame.time.wait(rand) self.play_after_delay(sound_item.sound, rand, loops) print "Playing sound: " + name
def __init__(self,value="C",secs=0.5,octave=4, sampleRate=44100, bits=16, name='', autoLog=True): """ """ self.name=name#only needed for autoLogging self.autoLog=autoLog #check initialisation if not mixer.get_init(): pygame.mixer.init(sampleRate, -16, 2, 3072) inits = mixer.get_init() if inits is None: init() inits = mixer.get_init() self.sampleRate, self.format, self.isStereo = inits #try to create sound self._snd=None self.setSound(value=value, secs=secs, octave=octave)
def todo_test_init__zero_values(self): # Ensure that argument values of 0 are replaced with # preset values. No way to check buffer size though. mixer.pre_init(44100, 8, 1) # None default values mixer.init(0, 0, 0) try: self.failUnlessEqual(mixer.get_init(), (44100, 8, 1)) finally: mixer.quit() mixer.pre_init(0, 0, 0, 0)
def test_sound_mixer(self): """Tests that the app can initialize the pygame audio mixer.""" import pygame.mixer as mix mix.init() # check that the mixer initialized self.assertIsNotNone(mix.get_init()) # try to play a sound mix.music.load(settings.ARMED_SOUND_FILE) mix.music.play() while mix.music.get_busy(): continue mix.quit()
def init_sound(experiment): print( u"openexp.sampler._legacy.init_sound(): sampling freq = %d, buffer size = %d" \ % (experiment.sound_freq, experiment.sound_buf_size)) if hasattr(mixer, u'get_init') and mixer.get_init(): print( u'openexp.sampler._legacy.init_sound(): mixer already initialized, closing') pygame.mixer.quit() mixer.pre_init(experiment.sound_freq, experiment.sound_sample_size, \ experiment.sound_channels, experiment.sound_buf_size) mixer.init()
def __init__(self,value="C",secs=0.5,octave=4, sampleRate=44100, bits=16, name='', autoLog=True, loops=0): """ """ self.name=name#only needed for autoLogging self.autoLog=autoLog #check initialisation if not mixer.get_init(): pygame.mixer.init(sampleRate, -16, 2, 3072) inits = mixer.get_init() if inits is None: init() inits = mixer.get_init() self.sampleRate, self.format, self.isStereo = inits #try to create sound self._snd=None #distinguish the loops requested from loops actual because of infinite tones # (which have many loops but none requested) self.requestedLoops = self.loops = int(loops) #-1 for infinite or a number of loops self.setSound(value=value, secs=secs, octave=octave)
def _check_quit(self): """Quit the mixer if not running a program and sound quiet for a while.""" if self.next_tone != [None, None, None, None]: self.quiet_ticks = 0 else: self.quiet_ticks += 1 if not self._persist and self.quiet_ticks > self.quiet_quit: # mixer is quiet and we're not running a program. # quit to reduce pulseaudio cpu load # this takes quite a while and leads to missed frames... if mixer.get_init() is not None: mixer.quit() self.quiet_ticks = 0
def check_quit(): """ Quit the mixer if not running a program and sound quiet for a while. """ global quiet_ticks if next_tone != [None, None, None, None]: quiet_ticks = 0 else: quiet_ticks += 1 if not persist and quiet_ticks > quiet_quit: # mixer is quiet and we're not running a program. # quit to reduce pulseaudio cpu load # this takes quite a while and leads to missed frames... if mixer.get_init() is not None: mixer.quit() quiet_ticks = 0
def alt_1_pushed(self): if self.data[1]!='': if mixer.get_init()!=None: if self.mp3media[1]!=None: mixer.music.load(self.mp3media[1]) mixer.music.set_volume(config.config['mp3_volume'] / 100.0) mixer.music.play() config.config['mascot'] = self.data[1] self.setPixmaps() self.width = int(self.pixmaps[0].width() * config.config['picture_scale']) self.height = int(self.pixmaps[0].height() * config.config['picture_scale']) self.resize(self.width, self.height) self.label.setGeometry(QtCore.QRect(0, 0, self.width, self.height)) config.write()
def init_sound(experiment): """ Initializes the pygame mixer before the experiment begins. Arguments: experiment -- An instance of libopensesame.experiment.experiment """ print "openexp.sampler._legacy.init_sound(): sampling freq = %d, buffer size = %d" \ % (experiment.sound_freq, experiment.sound_buf_size) if hasattr(mixer, 'get_init') and mixer.get_init(): print 'openexp.sampler._legacy.init_sound(): mixer already initialized, closing' pygame.mixer.quit() mixer.pre_init(experiment.sound_freq, experiment.sound_sample_size, \ experiment.sound_channels, experiment.sound_buf_size) mixer.init()
def __init__(self): pygame.mixer.pre_init(44100, -16, 2, 2048) pygame.mixer.init() """self.channel1 = Channel(0) self.channel2 = Channel(1) self.channel3 = Channel(2) self.channel4 = Channel(3) self.channel5 = Channel(4) self.channel6 = Channel(5) self.channel7 = Channel(6) self.channel8 = Channel(7)""" if mixer.get_init(): print "Mixer initialized." print "SoundController initialized."
def play(self, event): from pygame import mixer if not mixer.get_init(): mixer.init() if mixer.get_busy() and self.sound: self.sound.stop() return volume_attr = self.aguidata.get("volume") if volume_attr: volume = getattr(self.window.object, volume_attr) else: volume = 1 try: sound = get_sound(self.get_control_value(), volume=volume) sound.play() self.sound = sound except: self.sound = None self.play_button_down = True self.looping = False wx.CallLater(0.1, self.test_button) event.Skip()
def stageMusic(etage): if not mixer.get_init(): mixer.init() global listeMusiqueEtage playMusic(listeMusiqueEtage[etage], -1)
def __init__(self,path): self.path=path self.is_playing=False if( not mx.get_init()): mx.init()
def mp3volumeChanged(self): config.config['mp3_volume'] = self.horizontalSlider_5.value() if mixer.get_init()!=None: mixer.music.set_volume(config.config['mp3_volume'])
RSGlobals.down_held = False elif key == GLUT_KEY_LEFT: RSGlobals.left_held = False elif key == GLUT_KEY_RIGHT: RSGlobals.right_held = False elif key == GLUT_KEY_PAGE_UP: RSGlobals.zoom = max(1, RSGlobals.zoom - 1) elif key == GLUT_KEY_PAGE_DOWN: RSGlobals.zoom = min(25, RSGlobals.zoom + 1) glutPostRedisplay() if __name__ == "__main__": glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(640, 640) RSGlobals.window_id = glutCreateWindow(b"Hello, Kate") pygame.init() mixer.get_init() mixer.music.load('sounds/nyancat.mp3') mixer.music.play(-1) glutDisplayFunc(display) glutReshapeFunc(reshape) glutKeyboardFunc(keyboard) glutSpecialFunc(special) glutSpecialUpFunc(specialUp) glutIdleFunc(display) glutMainLoop()
def __init__(self, uniquechannel: bool = True, frequency: int = 22050, size: int = -16, channels: int = 2, buffer: int = 4096, devicename: str = '', allowedchanges: int = AUDIO_ALLOW_CHANNELS_CHANGE | AUDIO_ALLOW_FREQUENCY_CHANGE, force_init: bool = False) -> None: assert isinstance(uniquechannel, bool) assert isinstance(frequency, int) assert isinstance(size, int) assert isinstance(channels, int) assert isinstance(buffer, int) assert isinstance(devicename, str) assert isinstance(allowedchanges, int) assert isinstance(force_init, bool) assert frequency > 0, 'frequency must be greater than zero' assert channels > 0, 'channels must be greater than zero' assert buffer > 0, 'buffer size must be greater than zero' # Initialize sounds if not initialized if (mixer.get_init() is None and not SOUND_INITIALIZED[0]) or force_init: # Set sound as initialized globally SOUND_INITIALIZED[0] = True # Check pygame version version_major, _, version_minor = pygame_version # noinspection PyBroadException try: # <= 1.9.4 if version_major == 1 and version_minor <= 4: mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer) # <2.0.0 & >= 1.9.5 elif version_major == 1 and version_minor > 4: # lgtm [py/redundant-comparison] mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer, devicename=devicename) # >= 2.0.0 elif version_major > 1: mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer, devicename=devicename, allowedchanges=allowedchanges) except Exception as e: print('sound error: ' + str(e)) except pygame_error as e: print('sound engine could not be initialized, pygame error: ' + str(e)) # Store mixer configs self._mixer_configs = { 'allowedchanges': allowedchanges, 'buffer': buffer, 'channels': channels, 'devicename': devicename, 'frequency': frequency, 'size': size } # Channel where a sound is played self._channel = None self._uniquechannel = uniquechannel # Sound dict self._sound = {} for sound in SOUND_TYPES: self._sound[sound] = {} # Last played song self._last_play = '' self._last_time = 0
def test_get_init__returns_None_if_mixer_not_initialized(self): self.assert_(mixer.get_init() is None)
def NEWBUF_export_check(self): freq, fmt, channels = mixer.get_init() if channels == 1: ndim = 1 else: ndim = 2 itemsize = abs(fmt) // 8 formats = {8: 'B', -8: 'b', 16: '=H', -16: '=h', 32: '=I', -32: '=i', # 32 and 64 for future consideration 64: '=Q', -64: '=q'} format = formats[fmt] buftools = self.buftools Exporter = buftools.Exporter Importer = buftools.Importer is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN fsys, frev = ('<', '>') if is_lil_endian else ('>', '<') shape = (10, channels)[:ndim] strides = (channels * itemsize, itemsize)[2 - ndim:] exp = Exporter(shape, format=frev + 'i') snd = mixer.Sound(array=exp) buflen = len(exp) * itemsize * channels imp = Importer(snd, buftools.PyBUF_SIMPLE) self.assertEqual(imp.ndim, 0) self.assertTrue(imp.format is None) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertTrue(imp.shape is None) self.assertTrue(imp.strides is None) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_WRITABLE) self.assertEqual(imp.ndim, 0) self.assertTrue(imp.format is None) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertTrue(imp.shape is None) self.assertTrue(imp.strides is None) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_FORMAT) self.assertEqual(imp.ndim, 0) self.assertEqual(imp.format, format) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertTrue(imp.shape is None) self.assertTrue(imp.strides is None) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_ND) self.assertEqual(imp.ndim, ndim) self.assertTrue(imp.format is None) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertEqual(imp.shape, shape) self.assertTrue(imp.strides is None) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_STRIDES) self.assertEqual(imp.ndim, ndim) self.assertTrue(imp.format is None) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertEqual(imp.shape, shape) self.assertEqual(imp.strides, strides) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_FULL_RO) self.assertEqual(imp.ndim, ndim) self.assertEqual(imp.format, format) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, 2) self.assertEqual(imp.shape, shape) self.assertEqual(imp.strides, strides) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_FULL_RO) self.assertEqual(imp.ndim, ndim) self.assertEqual(imp.format, format) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertEqual(imp.shape, exp.shape) self.assertEqual(imp.strides, strides) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_C_CONTIGUOUS) self.assertEqual(imp.ndim, ndim) self.assertTrue(imp.format is None) self.assertEqual(imp.strides, strides) imp = Importer(snd, buftools.PyBUF_ANY_CONTIGUOUS) self.assertEqual(imp.ndim, ndim) self.assertTrue(imp.format is None) self.assertEqual(imp.strides, strides) if (ndim == 1): imp = Importer(snd, buftools.PyBUF_F_CONTIGUOUS) self.assertEqual(imp.ndim, 1) self.assertTrue(imp.format is None) self.assertEqual(imp.strides, strides) else: self.assertRaises(BufferError, Importer, snd, buftools.PyBUF_F_CONTIGUOUS)
def setVolumeMusic(): global volumeGlobal, volumeMusique if not mixer.get_init(): mixer.init() mixer.music.set_volume(float(volumeGlobal) * float(volumeMusic) / 10000)
def main(arraytype=None): """play various sndarray effects If arraytype is provided then use that array package. Valid values are 'numeric' or 'numpy'. Otherwise default to NumPy, or fall back on Numeric if NumPy is not installed. """ main_dir = os.path.split(os.path.abspath(__file__))[0] if arraytype not in ('numpy', None): raise ValueError('Array type not supported: %r' % arraytype) print("Using %s array package" % sndarray.get_arraytype()) print("mixer.get_init %s" % (mixer.get_init(), )) inited = mixer.get_init() samples_per_second = pygame.mixer.get_init()[0] print(("-" * 30) + "\n") print("loading sound") sound = mixer.Sound(os.path.join(main_dir, 'data', 'car_door.wav')) print("-" * 30) print("start positions") print("-" * 30) start_pos = 0.1 sound2 = sound_from_pos(sound, start_pos, samples_per_second) print("sound.get_length %s" % (sound.get_length(), )) print("sound2.get_length %s" % (sound2.get_length(), )) sound2.play() while mixer.get_busy(): pygame.time.wait(200) print("waiting 2 seconds") pygame.time.wait(2000) print("playing original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print("waiting 2 seconds") pygame.time.wait(2000) if 0: #TODO: this is broken. print(("-" * 30) + "\n") print("Slow down the original sound.") rate = 0.2 slowed_sound = slow_down_sound(sound, rate) slowed_sound.play() while mixer.get_busy(): pygame.time.wait(200) print("-" * 30) print("echoing") print("-" * 30) t1 = time.time() sound2 = make_echo(sound, samples_per_second) print("time to make echo %i" % (time.time() - t1, )) print("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print("echoed sound") sound2.play() while mixer.get_busy(): pygame.time.wait(200) sound = mixer.Sound(os.path.join(main_dir, 'data', 'secosmic_lo.wav')) t1 = time.time() sound3 = make_echo(sound, samples_per_second) print("time to make echo %i" % (time.time() - t1, )) print("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print("echoed sound") sound3.play() while mixer.get_busy(): pygame.time.wait(200)
def __init__(self, uniquechannel=True, frequency=22050, size=-16, channels=2, buffer=4096, devicename=None, allowedchanges=_AUDIO_ALLOW_CHANNELS_CHANGE | _AUDIO_ALLOW_FREQUENCY_CHANGE): """ Constructor. :param uniquechannel: Force the channel to be unique, this is setted at the moment of creation of the object. :type uniquechannel: bool :param frequency: Frequency of sounds :type frequency: int :param size: Size of sample :type size: int :param channels: Number of channels by default :type channels: int :param buffer: Buffer size :type buffer: int :param devicename: Device name :type devicename: NoneType, basestring :param allowedchanges: Convert the samples at runtime :type allowedchanges: bool """ assert isinstance(uniquechannel, bool) assert isinstance(frequency, int) assert isinstance(size, int) assert isinstance(channels, int) assert isinstance(buffer, int) assert isinstance(devicename, (type(None), str)) assert isinstance(allowedchanges, int) assert frequency > 0, 'frequency must be greater than zero' assert channels > 0, 'channels must be greater than zero' assert buffer > 0, 'buffer size must be greater than zero' # Initialize sounds if not initialized if _mixer.get_init() is None: _mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer, devicename=devicename, allowedchanges=allowedchanges) # Channel where a sound is played self._channel = None self._uniquechannel = uniquechannel # Sound dict self._type_sounds = [ SOUND_TYPE_CLICK_MOUSE, SOUND_TYPE_CLOSE_MENU, SOUND_TYPE_ERROR, SOUND_TYPE_EVENT, SOUND_TYPE_EVENT_ERROR, SOUND_TYPE_KEY_ADDITION, SOUND_TYPE_KEY_DELETION, SOUND_TYPE_OPEN_MENU ] self._sound = {} for sound in self._type_sounds: self._sound[sound] = {} # Last played song self._last_play = 0 self._last_time = 0
def test_get_init__returns_None_if_mixer_not_initialized(self): self.assertIsNone(mixer.get_init())
def test_array_keyword(self): try: from numpy import (array, arange, zeros, int8, uint8, int16, uint16, int32, uint32) except ImportError: return freq = 22050 format_list = [-8, 8, -16, 16] channels_list = [1, 2] a_lists = dict((f, []) for f in format_list) a32u_mono = arange(0, 256, 1, uint32) a16u_mono = a32u_mono.astype(uint16) a8u_mono = a32u_mono.astype(uint8) au_list_mono = [(1, a) for a in [a8u_mono, a16u_mono, a32u_mono]] for format in format_list: if format > 0: a_lists[format].extend(au_list_mono) a32s_mono = arange(-128, 128, 1, int32) a16s_mono = a32s_mono.astype(int16) a8s_mono = a32s_mono.astype(int8) as_list_mono = [(1, a) for a in [a8s_mono, a16s_mono, a32s_mono]] for format in format_list: if format < 0: a_lists[format].extend(as_list_mono) a32u_stereo = zeros([a32u_mono.shape[0], 2], uint32) a32u_stereo[:, 0] = a32u_mono a32u_stereo[:, 1] = 255 - a32u_mono a16u_stereo = a32u_stereo.astype(uint16) a8u_stereo = a32u_stereo.astype(uint8) au_list_stereo = [(2, a) for a in [a8u_stereo, a16u_stereo, a32u_stereo]] for format in format_list: if format > 0: a_lists[format].extend(au_list_stereo) a32s_stereo = zeros([a32s_mono.shape[0], 2], int32) a32s_stereo[:, 0] = a32s_mono a32s_stereo[:, 1] = -1 - a32s_mono a16s_stereo = a32s_stereo.astype(int16) a8s_stereo = a32s_stereo.astype(int8) as_list_stereo = [(2, a) for a in [a8s_stereo, a16s_stereo, a32s_stereo]] for format in format_list: if format < 0: a_lists[format].extend(as_list_stereo) for format in format_list: for channels in channels_list: try: mixer.init(freq, format, channels) except pygame.error: # Some formats (e.g. 16) may not be supported. continue try: __, f, c = mixer.get_init() if f != format or c != channels: # Some formats (e.g. -8) may not be supported. continue for c, a in a_lists[format]: self._test_array_argument(format, a, c == channels) finally: mixer.quit()
def test_init__zero_values(self): # Ensure that argument values of 0 are replaced with # preset values. No way to check buffer size though. mixer.pre_init(44100, 8, 1) # None default values mixer.init(0, 0, 0) self.assertEqual(mixer.get_init(), (44100, 8, 1))
if __name__=='__main__': mix.pre_init(frequency=44100, size=-16, channels=2, buffer=4096) pygame.init() width = 650 height = 550 fenetre = pygame.display.set_mode((width, height)) image_fond = pygame.image.load("01_Colordrilos_-_DJ_Sliver.jpg") fond = image_fond.convert() fenetre.blit(fond,(0,0)) print(mix.get_init()) continuer = 1 # Variable de boucle listDir = [] listDir.append(os.path.join("samples","Drums")) listDir.append(os.path.join("samples", "Bass")) listDir.append(os.path.join("samples", "Melodies")) buttons = [] for i in range(len(listDir)): d = listDir[i] files = os.listdir(d)
def playMusic(nom, boucle=0): """Joue une musique un certain nombre de fois""" if not mixer.get_init(): mixer.init() mixer.music.load('Musiques/' + nom + '.ogg') mixer.music.play(boucle)
def setUp(cls): # This makes sure the mixer is always initialized before each test (in # case a test calls pygame.mixer.quit()). if mixer.get_init() is None: mixer.init()
#!/usr/bin/env python """ sound_handler.py Created by Chandler Norris May 2, 2020 This is a basic sound handler to consolidate all sounds into one place. """ from pygame import mixer from os import path if not mixer.get_init(): mixer.init() SOUND_FOLDER = "data\\Sounds" SOUND_VOLUME = 1.0 MAX_SOUNDS = 2 # This is the sound list that you will add sounds to. It needs to load # EX: SOUND_LIST = {"test": mixer.Sound(path.join(SOUND_FOLDER, "horn.mp3"))} SOUND_LIST = {} def play_sound(sound, loops=1): if sound in SOUND_LIST: if SOUND_LIST[sound].get_num_channels() < MAX_SOUNDS: SOUND_LIST[sound].set_volume(SOUND_VOLUME) SOUND_LIST[sound].play(loops) def stop_sound(sound): if sound in SOUND_LIST: SOUND_LIST[sound].stop()
def test_array_keyword(self): try: from numpy import (array, arange, zeros, int8, uint8, int16, uint16, int32, uint32) except ImportError: return freq = 22050 format_list = [-8, 8, -16, 16] channels_list = [1, 2] a_lists = dict((f, []) for f in format_list) a32u_mono = arange(0, 256, 1, uint32) a16u_mono = a32u_mono.astype(uint16) a8u_mono = a32u_mono.astype(uint8) au_list_mono = [(1, a) for a in [a8u_mono, a16u_mono, a32u_mono]] for format in format_list: if format > 0: a_lists[format].extend(au_list_mono) a32s_mono = arange(-128, 128, 1, int32) a16s_mono = a32s_mono.astype(int16) a8s_mono = a32s_mono.astype(int8) as_list_mono = [(1, a) for a in [a8s_mono, a16s_mono, a32s_mono]] for format in format_list: if format < 0: a_lists[format].extend(as_list_mono) a32u_stereo = zeros([a32u_mono.shape[0], 2], uint32) a32u_stereo[:,0] = a32u_mono a32u_stereo[:,1] = 255 - a32u_mono a16u_stereo = a32u_stereo.astype(uint16) a8u_stereo = a32u_stereo.astype(uint8) au_list_stereo = [(2, a) for a in [a8u_stereo, a16u_stereo, a32u_stereo]] for format in format_list: if format > 0: a_lists[format].extend(au_list_stereo) a32s_stereo = zeros([a32s_mono.shape[0], 2], int32) a32s_stereo[:,0] = a32s_mono a32s_stereo[:,1] = -1 - a32s_mono a16s_stereo = a32s_stereo.astype(int16) a8s_stereo = a32s_stereo.astype(int8) as_list_stereo = [(2, a) for a in [a8s_stereo, a16s_stereo, a32s_stereo]] for format in format_list: if format < 0: a_lists[format].extend(as_list_stereo) for format in format_list: for channels in channels_list: try: mixer.init(freq, format, channels) except pygame.error: # Some formats (e.g. 16) may not be supported. continue try: __, f, c = mixer.get_init() if f != format or c != channels: # Some formats (e.g. -8) may not be supported. continue for c, a in a_lists[format]: self._test_array_interface(format, a, c == channels) finally: mixer.quit()
def __init__(self, uniquechannel=True, frequency=22050, size=-16, channels=2, buffer=4096, devicename='', allowedchanges=AUDIO_ALLOW_CHANNELS_CHANGE | AUDIO_ALLOW_FREQUENCY_CHANGE, force_init=False): assert isinstance(uniquechannel, bool) assert isinstance(frequency, int) assert isinstance(size, int) assert isinstance(channels, int) assert isinstance(buffer, int) assert isinstance(devicename, str) assert isinstance(allowedchanges, int) assert isinstance(force_init, bool) assert frequency > 0, 'frequency must be greater than zero' assert channels > 0, 'channels must be greater than zero' assert buffer > 0, 'buffer size must be greater than zero' # Initialize sounds if not initialized if (mixer.get_init() is None and not SOUND_INITIALIZED[0]) or force_init: # Set sound as initialized globally SOUND_INITIALIZED[0] = True # Check pygame version version_major, _, version_minor = pygame_version # noinspection PyBroadException try: # <= 1.9.4 if version_major == 1 and version_minor <= 4: mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer) # <2.0.0 & >= 1.9.5 elif version_major == 1 and version_minor > 4: # lgtm [py/redundant-comparison] mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer, devicename=devicename) # >= 2.0.0 elif version_major > 1: mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer, devicename=devicename, allowedchanges=allowedchanges) except Exception as e: print('sound error: ' + str(e)) except pygame_error as e: print('sound engine could not be initialized, pygame error: ' + str(e)) # Channel where a sound is played self._channel = None # type: (mixer.Channel,None) self._uniquechannel = uniquechannel # Sound dict self._type_sounds = [ SOUND_TYPE_CLICK_MOUSE, SOUND_TYPE_CLOSE_MENU, SOUND_TYPE_ERROR, SOUND_TYPE_EVENT, SOUND_TYPE_EVENT_ERROR, SOUND_TYPE_KEY_ADDITION, SOUND_TYPE_KEY_DELETION, SOUND_TYPE_OPEN_MENU, SOUND_TYPE_WIDGET_SELECTION ] self._sound = {} for sound in self._type_sounds: self._sound[sound] = {} # Last played song self._last_play = 0 self._last_time = 0 # Other (dev) self._verbose = True
def __init__(self, uniquechannel=True, frequency=22050, size=-16, channels=2, buffer=4096, devicename='', allowedchanges=_AUDIO_ALLOW_CHANNELS_CHANGE | _AUDIO_ALLOW_FREQUENCY_CHANGE, force_init=False): """ Constructor. :param uniquechannel: Force the channel to be unique, this is setted at the moment of creation of the object :type uniquechannel: bool :param frequency: Frequency of sounds :type frequency: int :param size: Size of sample :type size: int :param channels: Number of channels by default :type channels: int :param buffer: Buffer size :type buffer: int :param devicename: Device name :type devicename: basestring :param allowedchanges: Convert the samples at runtime, only in pygame>=2.0.0 :type allowedchanges: bool :param force_init: Force mixer init with new parameters :type force_init: bool """ assert isinstance(uniquechannel, bool) assert isinstance(frequency, int) assert isinstance(size, int) assert isinstance(channels, int) assert isinstance(buffer, int) assert isinstance(devicename, str) assert isinstance(allowedchanges, int) assert isinstance(force_init, bool) assert frequency > 0, 'frequency must be greater than zero' assert channels > 0, 'channels must be greater than zero' assert buffer > 0, 'buffer size must be greater than zero' # Initialize sounds if not initialized if (_mixer.get_init() is None and SOUND_INITIALIZED[0] is False) or force_init: # Set sound as initialized globally SOUND_INITIALIZED[0] = True # Check pygame version version_major, _, version_minor = _pygame_version # noinspection PyBroadException try: # <= 1.9.4 if version_major == 1 and version_minor <= 4: _mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer) # <2.0.0 & >= 1.9.5 elif version_major == 1 and version_minor > 4: # lgtm [py/redundant-comparison] _mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer, devicename=devicename) # >= 2.0.0 elif version_major > 1: _mixer.init(frequency=frequency, size=size, channels=channels, buffer=buffer, devicename=devicename, allowedchanges=allowedchanges) except Exception as e: print('Sound error: ' + str(e)) except _pygame_error as e: print('Sound engine could not be initialized, pygame error: ' + str(e)) # Channel where a sound is played self._channel = None # type: _mixer.ChannelType self._uniquechannel = uniquechannel # Sound dict self._type_sounds = [ SOUND_TYPE_CLICK_MOUSE, SOUND_TYPE_CLOSE_MENU, SOUND_TYPE_ERROR, SOUND_TYPE_EVENT, SOUND_TYPE_EVENT_ERROR, SOUND_TYPE_KEY_ADDITION, SOUND_TYPE_KEY_DELETION, SOUND_TYPE_OPEN_MENU ] self._sound = {} for sound in self._type_sounds: self._sound[sound] = {} # Last played song self._last_play = 0 self._last_time = 0 # Other (dev) self._verbose = True
def _set_volume(self): """Set the volume of the audio samples.""" if mixer.get_init(): mixer.music.set_volume( self._volume.value() / self._volume.maximum() )
import math import numpy import pygame.sndarray as sound import pygame.mixer as mixer mixer.init() print(mixer.get_init()) SAMPLERATE = 44100 # ar = numpy.array([[0.5, 0.5], [2, 2], [3, 3]], dtype='int8') def tone(freq=1000, volume=127, length=1): num_steps = length * SAMPLERATE s = [] for n in range(num_steps): value = int( math.sin(n * freq * (6.28318 / SAMPLERATE) * length) * volume) print(value) s.append([value, value]) x_arr = numpy.array(s, dtype='int8') return x_arr sound.make_sound(tone())
def _check_init_mixer(self): """Initialise the mixer if necessary.""" if mixer.get_init() is None: mixer.init()
import math import random import pygame from pygame import mixer mixer.get_init() pygame.init() # screen decorating.... screen = pygame.display.set_mode((800, 500)) background = pygame.image.load("background.png") pygame.display.set_caption("COVID-19-Corona 2.0") icon = pygame.image.load("title.png") pygame.display.set_icon(icon) # players and enemies initials playerimg = pygame.image.load("player.png") enemy1img = [] enemy1X = [] enemy1Y = [] enemy1X_change = [] enemy1Y_change = [] num_enemy_1 = 3 num_enemy_2 = 3 enemy_speed = 5 for i in range(num_enemy_1): enemy1img.append(pygame.image.load("enemy.png")) enemy1X.append(random.randint(15, 770)) enemy1Y.append(random.randint(50, 150)) enemy1X_change.append(enemy_speed) enemy1Y_change.append(0) enemy2img = []
def __init__(self, allowedchanges: int = AUDIO_ALLOW_CHANNELS_CHANGE | AUDIO_ALLOW_FREQUENCY_CHANGE, buffer: int = 4096, channels: int = 2, devicename: str = '', force_init: bool = False, frequency: int = 22050, size: int = -16, sound_id: str = '', uniquechannel: bool = True) -> None: super(Sound, self).__init__(object_id=sound_id) assert isinstance(allowedchanges, int) assert isinstance(buffer, int) assert isinstance(channels, int) assert isinstance(devicename, str) assert isinstance(force_init, bool) assert isinstance(frequency, int) assert isinstance(size, int) assert isinstance(uniquechannel, bool) assert buffer > 0, 'buffer size must be greater than zero' assert channels > 0, 'channels must be greater than zero' assert frequency > 0, 'frequency must be greater than zero' # Check if mixer is init mixer_missing = 'MissingModule' in str(type(mixer)) if mixer_missing: warn('pygame mixer module could not be found, NotImplementedError' 'has been raised. Sound support is disabled') SOUND_INITIALIZED[1] = False # Initialize sounds if not initialized if not mixer_missing and \ ((mixer.get_init() is None and not SOUND_INITIALIZED[0]) or force_init): # Set sound as initialized globally SOUND_INITIALIZED[0] = True # Check pygame version version_major, _, version_minor = pygame_version # noinspection PyBroadException try: # pygame < 1.9.5 mixer_kwargs = { 'frequency': frequency, 'size': size, 'channels': channels, 'buffer': buffer } # pygame >= 1.9.5 if (version_major == 1 and version_minor > 4) or version_major > 1: mixer_kwargs['devicename'] = devicename # pygame >= 2.0.0 if version_major > 1: mixer_kwargs['allowedchanges'] = allowedchanges # Call to mixer mixer.init(**mixer_kwargs) except Exception as e: warn('sound error: ' + str(e)) except pygame_error as e: warn('sound engine could not be initialized, pygame error: ' + str(e)) # Store mixer configs self._mixer_configs = { 'allowedchanges': allowedchanges, 'buffer': buffer, 'channels': channels, 'devicename': devicename, 'frequency': frequency, 'size': size } # Channel where a sound is played self._channel = None self._uniquechannel = uniquechannel # Sound dict self._sound = {} for sound in SOUND_TYPES: self._sound[sound] = {} # Last played song self._last_play = '' self._last_time = 0
def main(arraytype=None): """play various sndarray effects If arraytype is provided then use that array package. Valid values are 'numeric' or 'numpy'. Otherwise default to NumPy, or fall back on Numeric if NumPy is not installed. """ main_dir = os.path.split(os.path.abspath(__file__))[0] if arraytype not in ('numpy', None): raise ValueError('Array type not supported: %r' % arraytype) print ("Using %s array package" % sndarray.get_arraytype()) print ("mixer.get_init %s" % (mixer.get_init(),)) inited = mixer.get_init() samples_per_second = pygame.mixer.get_init()[0] print (("-" * 30) + "\n") print ("loading sound") sound = mixer.Sound(os.path.join(main_dir, 'data', 'car_door.wav')) print ("-" * 30) print ("start positions") print ("-" * 30) start_pos = 0.1 sound2 = sound_from_pos(sound, start_pos, samples_per_second) print ("sound.get_length %s" % (sound.get_length(),)) print ("sound2.get_length %s" % (sound2.get_length(),)) sound2.play() while mixer.get_busy(): pygame.time.wait(200) print ("waiting 2 seconds") pygame.time.wait(2000) print ("playing original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("waiting 2 seconds") pygame.time.wait(2000) if 0: #TODO: this is broken. print (("-" * 30) + "\n") print ("Slow down the original sound.") rate = 0.2 slowed_sound = slow_down_sound(sound, rate) slowed_sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("-" * 30) print ("echoing") print ("-" * 30) t1 = time.time() sound2 = make_echo(sound, samples_per_second) print ("time to make echo %i" % (time.time() - t1,)) print ("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("echoed sound") sound2.play() while mixer.get_busy(): pygame.time.wait(200) sound = mixer.Sound(os.path.join(main_dir, 'data', 'secosmic_lo.wav')) t1 = time.time() sound3 = make_echo(sound, samples_per_second) print ("time to make echo %i" % (time.time() - t1,)) print ("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("echoed sound") sound3.play() while mixer.get_busy(): pygame.time.wait(200)
def stopMusic(): """Arrête la musique""" if not mixer.get_init(): mixer.init() mixer.music.stop()
def _NEWBUF_export_check(self): freq, fmt, channels = mixer.get_init() ndim = 1 if (channels == 1) else 2 itemsize = abs(fmt) // 8 formats = { 8: 'B', -8: 'b', 16: '=H', -16: '=h', 32: '=I', -32: '=i', # 32 and 64 for future consideration 64: '=Q', -64: '=q' } format = formats[fmt] from pygame.tests.test_utils import buftools Exporter = buftools.Exporter Importer = buftools.Importer is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN fsys, frev = ('<', '>') if is_lil_endian else ('>', '<') shape = (10, channels)[:ndim] strides = (channels * itemsize, itemsize)[2 - ndim:] exp = Exporter(shape, format=frev + 'i') snd = mixer.Sound(array=exp) buflen = len(exp) * itemsize * channels imp = Importer(snd, buftools.PyBUF_SIMPLE) self.assertEqual(imp.ndim, 0) self.assertTrue(imp.format is None) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertTrue(imp.shape is None) self.assertTrue(imp.strides is None) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_WRITABLE) self.assertEqual(imp.ndim, 0) self.assertTrue(imp.format is None) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertTrue(imp.shape is None) self.assertTrue(imp.strides is None) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_FORMAT) self.assertEqual(imp.ndim, 0) self.assertEqual(imp.format, format) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertTrue(imp.shape is None) self.assertTrue(imp.strides is None) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_ND) self.assertEqual(imp.ndim, ndim) self.assertTrue(imp.format is None) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertEqual(imp.shape, shape) self.assertTrue(imp.strides is None) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_STRIDES) self.assertEqual(imp.ndim, ndim) self.assertTrue(imp.format is None) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertEqual(imp.shape, shape) self.assertEqual(imp.strides, strides) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_FULL_RO) self.assertEqual(imp.ndim, ndim) self.assertEqual(imp.format, format) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, 2) self.assertEqual(imp.shape, shape) self.assertEqual(imp.strides, strides) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_FULL_RO) self.assertEqual(imp.ndim, ndim) self.assertEqual(imp.format, format) self.assertEqual(imp.len, buflen) self.assertEqual(imp.itemsize, itemsize) self.assertEqual(imp.shape, exp.shape) self.assertEqual(imp.strides, strides) self.assertTrue(imp.suboffsets is None) self.assertFalse(imp.readonly) self.assertEqual(imp.buf, snd._samples_address) imp = Importer(snd, buftools.PyBUF_C_CONTIGUOUS) self.assertEqual(imp.ndim, ndim) self.assertTrue(imp.format is None) self.assertEqual(imp.strides, strides) imp = Importer(snd, buftools.PyBUF_ANY_CONTIGUOUS) self.assertEqual(imp.ndim, ndim) self.assertTrue(imp.format is None) self.assertEqual(imp.strides, strides) if ndim == 1: imp = Importer(snd, buftools.PyBUF_F_CONTIGUOUS) self.assertEqual(imp.ndim, 1) self.assertTrue(imp.format is None) self.assertEqual(imp.strides, strides) else: self.assertRaises(BufferError, Importer, snd, buftools.PyBUF_F_CONTIGUOUS)