def _array_samples(sound, raw): # Info is a (freq, format, stereo) tuple info = mixer.query_spec ()[1:] if not info: raise pygame2.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 samples (sound): """pygame2._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 pygame2.mixer.get_init(). """ # Info is a (freq, format, stereo) tuple info = mixer.query_spec ()[1:] if not info: raise pygame2.Error ("Mixer not initialized") fmtbytes = (abs (info[1]) & 0xff) >> 3 channels = info[2] data = sound.get_buffer () shape = (data.length // 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 -8 : numpy.int8, # AUDIO_S8 -16 : numpy.int16 # AUDUI_S16 }[info[1]] soundarray = numpy.frombuffer (data, typecode) soundarray.shape = shape return soundarray
def make_sound (soundarray): """pygame2._numpysndarray.make_sound(soundarray): 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 = mixer.query_spec ()[1:] if not info: raise pygame2.Error ("Mixer not initialized") channels = info[2] shape = soundarray.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 (soundarray)