def playAudio(output, sample_rate=44100): mixer.init(sample_rate) preview = output.copy(order='C') preview = sndarray.make_sound(preview.astype(np.int16)) preview.play() return mixer, preview
def play_audio(samples, wait_for_end=False): """ Uses PyGame to play the audio samples given as a list of samples. """ init_mixer() from pygame.mixer import music from pygame.sndarray import make_sound from pygame import USEREVENT, event import numpy # Prepare the wave data to play # Make it stereo and the right number format smp_array = numpy.array(zip(samples,samples)).astype(numpy.int16) # Generate the sound object from the sample array snd = make_sound(smp_array) # Set it playing channel = snd.play() # Set an event to be triggered when the music ends, so we can # wait for it if necessary channel.set_endevent(USEREVENT) if wait_for_end: # Wait until the music finishes event.wait()
def play_audio(samples, wait_for_end=False): """ Uses PyGame to play the audio samples given as a list of samples. """ init_mixer() from pygame.mixer import music from pygame.sndarray import make_sound from pygame import USEREVENT, event import numpy # Prepare the wave data to play # Make it stereo and the right number format smp_array = numpy.array(zip(samples, samples)).astype(numpy.int16) # Generate the sound object from the sample array snd = make_sound(smp_array) # Set it playing channel = snd.play() # Set an event to be triggered when the music ends, so we can # wait for it if necessary channel.set_endevent(USEREVENT) if wait_for_end: # Wait until the music finishes event.wait()
def slow_down_sound(sound, rate): """ returns a sound which is a slowed down version of the original. rate - at which the sound should be slowed down. eg. 0.5 would be half speed. """ raise NotImplementedError() grow_rate = 1 / rate # make it 1/rate times longer. a1 = sndarray.array(sound) surf = pygame.surfarray.make_surface(a1) print(a1.shape[0] * grow_rate) scaled_surf = pygame.transform.scale( surf, (int(a1.shape[0] * grow_rate), a1.shape[1])) print(scaled_surf) print(surf) a2 = a1 * rate print(a1.shape) print(a2.shape) print(a2) sound2 = sndarray.make_sound(a2.astype(int16)) return sound2
def _fromArray(self, thisArray): global usePygame #get a mixer.Sound object from an array of floats (-1:1) #make stereo if mono if self.isStereo==2 and \ (len(thisArray.shape)==1 or thisArray.shape[1]<2): tmp = numpy.ones((len(thisArray),2)) tmp[:,0] = thisArray tmp[:,1] = thisArray thisArray = tmp #get the format right if self.format == -16: thisArray= (thisArray*2**15).astype(numpy.int16) elif self.format == 16: thisArray= ((thisArray+1)*2**15).astype(numpy.uint16) elif self.format == -8: thisArray= (thisArray*2**7).astype(numpy.Int8) elif self.format == 8: thisArray= ((thisArray+1)*2**7).astype(numpy.uint8) self._snd = sndarray.make_sound(thisArray) return True
def makeSound(samplingFreq, data): """ Make a Player object from raw data returns a pygame.mixer.Sound object """ # Ugh! impurity pygame.mixer.init(frequency=samplingFreq) return make_sound(data)
def mouse_down(self, event): self.canvas.delete('all') self.prev = event self.sound_on = True self.sound = sndarray.make_sound(self.sine_wave(self.calc_freq(event.x))) self.sound.play(tempo_2) #Works as csound event biding self.canvas.create_text(self.canvas.winfo_width()//2, self.canvas.winfo_height()//7, anchor = 's', text = "Drawing...", font = ('Helvetica', 38, 'bold'), fill = 'black')
def make_echo(sound, samples_per_second, mydebug = True): """ returns a sound which is echoed of the last one. """ echo_length = 3.5 a1 = sndarray.array(sound) if mydebug: print ('SHAPE1: %s' % (a1.shape,)) length = a1.shape[0] #myarr = zeros(length+12000) myarr = zeros(a1.shape, int32) if len(a1.shape) > 1: mult = a1.shape[1] size = (a1.shape[0] + int(echo_length * a1.shape[0]), a1.shape[1]) #size = (a1.shape[0] + int(a1.shape[0] + (echo_length * 3000)), a1.shape[1]) else: mult = 1 size = (a1.shape[0] + int(echo_length * a1.shape[0]),) #size = (a1.shape[0] + int(a1.shape[0] + (echo_length * 3000)),) if mydebug: print (int(echo_length * a1.shape[0])) myarr = zeros(size, int32) if mydebug: print ("size %s" % (size,)) print (myarr.shape) myarr[:length] = a1 #print (myarr[3000:length+3000]) #print (a1 >> 1) #print ("a1.shape %s" % (a1.shape,)) #c = myarr[3000:length+(3000*mult)] #print ("c.shape %s" % (c.shape,)) incr = int(samples_per_second / echo_length) gap = length myarr[incr:gap+incr] += a1>>1 myarr[incr*2:gap+(incr*2)] += a1>>2 myarr[incr*3:gap+(incr*3)] += a1>>3 myarr[incr*4:gap+(incr*4)] += a1>>4 if mydebug: print ('SHAPE2: %s' % (myarr.shape,)) sound2 = sndarray.make_sound(myarr.astype(int16)) return sound2
def build_sound(pitch_key, duration): # pitch_key is MIDI pitch, an integer 0-127, eg A4 (440Hz) is 69 # duration is in seconds, int or float pitch_hz = hz_from_key(pitch_key) amplitude = 2**(_bits - 1) - 1 # 16 _bits, signed omega = 2 * math.pi * pitch_hz n_samples = int(round(duration * _freq)) samples = [ amplitude * math.sin(omega * j / _freq) for j in range(n_samples) ] arr = numpy.array(list(zip(samples, samples))) # stereo needs width of 2 sound = sndarray.make_sound(numpy.int16(arr)) return sound
def mouse_move(self, event): if self.sound_on: new_sound = sndarray.make_sound(self.sine_wave(self.calc_freq(event.x))) new_sound.play(infinite) #Infinte looping self.sound.stop() self.sound = new_sound Red = int(255 * event.x / self.canvas.winfo_width() * (self.canvas.winfo_height() - (event.y + 1)) / self.canvas.winfo_height()) Blues = int(255 * event.x / self.canvas.winfo_width() * (event.y + 1) / self.canvas.winfo_height()) if self.prev: # draw line if mouse is down self.canvas.create_line(self.prev.x, self.prev.y, event.x, event.y, width = 10, fill = '#{:02x}88{:02x}'.format(Red, Blues)) self.prev = event
def play_sound(x=None): fs = 8000 # Hz mixer.init() mixer.pre_init(fs, size=-16, channels=1) mixer.init() sound = sndarray.make_sound(x) sound.play() time.sleep( 10 ) # NOTE: Since sound playback is async, allow sound playback to start before Python exits
def mouse_move(self, event): if self.sound_on: new_sound = sndarray.make_sound(self.sine_wave(self.calc_freq(event.y))) new_sound.set_volume(self.calc_volume(event.x)) new_sound.play(-1) self.sound.stop() self.sound = new_sound R = int(255 * event.x / self.canvas.winfo_width() * (self.canvas.winfo_height() - (event.y + 1)) / self.canvas.winfo_height()) B = int(255 * event.x / self.canvas.winfo_width() * (event.y + 1) / self.canvas.winfo_height()) self.canvas.config(background = '#{:02x}50{:02x}'.format(R, B)) # set green to 0x50 for "pizzazz" if self.prev: # draw line if mouse is down self.canvas.create_line(self.prev.x, self.prev.y, event.x, event.y, width = 10, fill = '#{:02x}88{:02x}'.format(R, B)) self.prev = event
def __init__(self, wav, rate=44100, dur=10, amp=100, volume=1, delay=None): self.delay = delay self.sample_rate = rate if isinstance(wav, str): self.filename = wav self.get_file() elif isinstance(wav, np.ndarray): self.arr = wav self.duration = len(self.arr) * (self.sample_rate**-1) else: print("{} object type not supported yet".format(type(wav))) return mixer.init(self.sample_rate) self.player = self.arr.copy(order='C') self.player = sndarray.make_sound(self.player.astype('int16')) self.player.set_volume(volume) self.times = np.arange(0, self.duration, self.sample_rate**-1)
def generateNotes(self): self.parent.write("Generating notes...") for i in range(-36,60): for key in self.key: if i in key: if not os.path.exists(self.basicNote[:-4] + os.path.sep + str(i) + '.wav'): factor = 2**(1.0 * i / 12.0) if self.lengthAdjusted: (samplerate,smp)=paulstretch.load_wav( self.basicNote) paulstretch.paulstretch(samplerate, smp, factor, self.windowSize, self.basicNote[:-4]+"temp"+".wav") note = pgm.Sound(self.basicNote[:-4]+"temp"+".wav") else: note = pgm.Sound(self.basicNote) note.set_volume(0) note.play() basicNoteArray = pgsa.array(note) basicNoteResampled = [] for ch in range(basicNoteArray.shape[1]): sound_channel = basicNoteArray[:,ch] basicNoteResampled.append(np.array( self.speedx(sound_channel, factor))) basicNoteResampled = np.transpose(np.array( basicNoteResampled)).copy(order='C') noteOut = pgsa.make_sound(basicNoteResampled.astype( basicNoteArray.dtype)) noteFile = wave.open(self.basicNote[:-4] + os.path.sep + str(i) + '.wav', 'w') noteFile.setframerate(44100) noteFile.setnchannels(2) noteFile.setsampwidth(2) noteFile.writeframesraw(noteOut.get_raw()) noteFile.close() self.parent.write(self.parent.notes[ i%len(self.parent.notes)] + "(" + str(i//len(self.parent.notes)+5) + ") Generated!") if os.path.exists(self.basicNote[:-4]+"temp"+".wav"): os.remove(self.basicNote[:-4]+"temp"+".wav")
def make_echo(array_, mixer_samples_rate_): echo = 4 samples = array_.shape[0] # echo start e.g (31712 / 8) * 4 = 15856 start at 1/2 of the first sampling # freq = 44100 # period = 1 / freq = 22.6 u seconds # 15856 * 22.6 u seconds = 0.359 seconds (start of the first echo) start = int((samples / 8) * 8) print(start) total_time = echo * array_.shape[0] + start print(total_time) # size = (array_.shape[0] + int(echo_length * array_.shape[0]), array_.shape[1]) size = (total_time, array_.shape[1]) echoed_array = zeros(size, numpy.int16) echoed_array[0:samples] = array_ for i in range(echo): echoed_array[start * i:samples + start * i] += array_ >> i + 1 return sndarray.make_sound(echoed_array.astype(numpy.int16))
def slow_down_sound(sound, rate): """ returns a sound which is a slowed down version of the original. rate - at which the sound should be slowed down. eg. 0.5 would be half speed. """ raise NotImplementedError() grow_rate = 1 / rate # make it 1/rate times longer. a1 = sndarray.array(sound) surf = pygame.surfarray.make_surface(a1) print (a1.shape[0] * grow_rate) scaled_surf = pygame.transform.scale(surf, (int(a1.shape[0] * grow_rate), a1.shape[1])) print (scaled_surf) print (surf) a2 = a1 * rate print (a1.shape) print (a2.shape) print (a2) sound2 = sndarray.make_sound(a2.astype(int16)) return sound2
def expt4(): print '-------------------------' print 'Demo 2: Brain music' raw_input('This demo will record your brain signal for 15s and ' + 'play it back at 2x time speed (so you can hear it). \n' \ 'Hit enter to start.') data, blinks=startEEG(15, music=True) print 'One moment, playing your brain music...\n' mixer.quit() mixer.init(frequency=1024, size=-16, channels=1, buffer=4096) soundVals = [] file = open("brain_music.raw",'r') for line in file: soundVals.append(int(line.rstrip('\n').split(',')[1])) file.close() soundVals = array(soundVals) sound = sndarray.make_sound(soundVals) mixer.Sound.play(sound) while mixer.get_busy(): time.sleep(1) mixer.quit() raw_input('Hit enter to continue...') print('\n\n')
def expt4(): print '-------------------------' print 'Demo 2: Brain music' raw_input('This demo will record your brain signal for 15s and ' + 'play it back at 2x time speed (so you can hear it). \n' \ 'Hit enter to start.') data, blinks = startEEG(15, music=True) print 'One moment, playing your brain music...\n' mixer.quit() mixer.init(frequency=1024, size=-16, channels=1, buffer=4096) soundVals = [] file = open("brain_music.raw", 'r') for line in file: soundVals.append(int(line.rstrip('\n').split(',')[1])) file.close() soundVals = array(soundVals) sound = sndarray.make_sound(soundVals) mixer.Sound.play(sound) while mixer.get_busy(): time.sleep(1) mixer.quit() raw_input('Hit enter to continue...') print('\n\n')
#!/usr/bin/python # basado en # http://lists.canonical.org/pipermail/kragen-hacks/2007-November/000465.html from pygame import mixer, sndarray, time, init from Numeric import arange, Int16, sin, pi tasa = 22050 # de muestreo mixer.pre_init(tasa, -16, 1) # 16bit, un canal init() # necesario para mixer hz, pico, n_muestras = 440, 16384, tasa theta = arange(n_muestras) * (2*pi * hz / tasa) sndarray.make_sound((pico * sin(theta)).astype(Int16) ).play(-1, 0, 20) # 20ms fadein time.wait(1000) # un segundo
import pygame from scipy.io.wavfile import read from pygame.sndarray import make_sound import numpy as np pygame.mixer.pre_init(frequency=44100, channels=1) pygame.mixer.init() print(pygame.mixer.get_init()) rate, first_signal = read('D:\\phd\\DATA\\recordings\\01_ZL\\01_ZL_001.wav') _, second_signal = read('D:\\phd\\DATA\\recordings\\01_ZL\\01_ZL_002.wav') signal = np.concatenate((first_signal, second_signal)) signal += np.random.randint(-2**13, 2**13, size=signal.shape, dtype='int16') sound_object = make_sound(signal) pygame.mixer.stop() pygame.mixer.Sound(sound_object).play() # pygame.mixer.quit()
#!/usr/bin/python # basado en # http://lists.canonical.org/pipermail/kragen-hacks/2007-November/000465.html from pygame import mixer, sndarray, time, init from Numeric import arange, Int16, sin, pi tasa = 22050 # de muestreo def sinus(hz, pico, n_muestras): theta = arange(n_muestras) * (2*pi * hz / tasa) return (pico * sin(theta)).astype(Int16) mixer.pre_init(tasa, -16, 1) # 16bit, un canal init() sndarray.make_sound(sinus(440, 4096, tasa) + sinus(880, 4096, tasa) ).play(-1, 0, 20) # 20ms fadein time.wait(1000) # un segundo
def mouse_down(self, event): self.prev = event self.sound_on = True self.sound = sndarray.make_sound(self.sine_wave(self.calc_freq(event.y))) self.sound.set_volume(self.calc_volume(event.x)) self.sound.play(-1)
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())
send_byte(0) # playback truncate last 1/2 or so of audio x_arr = numpy.array(s, dtype="int16") return x_arr def calibrate(): ''' save a lengthy block of 0s for calibration purposes ''' for n in range(15000): send_byte(0) x_arr = numpy.array(s, dtype="int16") return x_arr if len(sys.argv) >= 2: ih = IntelHex(sys.argv[1]) snd = cass_save(ih) if len(sys.argv) == 2: # play right away make_sound(snd).play() sleep(num_bytes / 250) else: # save as WAV file sfile = wave.open(sys.argv[2], "w") sfile.setnchannels(1) sfile.setsampwidth(2) # 2 bytes sfile.setframerate(SAMPLERATE) sfile.setnframes(len(snd)) sfile.setcomptype('NONE', 'descrip') # No compression sfile.writeframes(snd.tostring()) sfile.close()
def play_sample(arr): snd = make_sound(arr.astype(np.int16)) Channel(0).queue(snd) wait_for_channels()
def beep(freq, duration): samples = (sin(arrayrange(duration/1000.0 * samplerate) * (2 * pi * (freq / samplerate))) * float(1 << (bits - 2))).astype(Int16) snd = sndarray.make_sound(samples) snd.play() while mixer.get_busy(): pass
def enqueueSamples(channel, an_array): channel.queue(snd.make_sound(an_array))
#!/usr/bin/python # basado en # http://lists.canonical.org/pipermail/kragen-hacks/2007-November/000465.html from pygame import mixer, sndarray, time, init from Numeric import arange, Int16, sin, pi tasa = 22050 # de muestreo def sinus(hz, pico, n_muestras): theta = arange(n_muestras) * (2*pi * hz / tasa) return (pico * sin(theta)).astype(Int16) mixer.pre_init(tasa, -16, 1) # 16bit, un canal init() reloj, sonido = time.Clock(), None for ii in range(1, 14): hz = 440 * pow(2, ii/12.0) n_muestras = 512 * tasa // hz muestras = sum(sinus(jj*hz, 512, n_muestras) for jj in [1, 1, 2, 2, 4, 8, 3, 5, 6][:ii]) nuevo = sndarray.make_sound(muestras) if sonido is not None: reloj.tick(1) # max 1 fps sonido.fadeout(20) # 20ms fadeout nuevo.play(-1, 2000, 20) # 2000ms max sonido = nuevo
def play(music): for beat in music: beat_wave = build_beat(beat) snd.make_sound(beat_wave).play() time.sleep(BEAT_LENGTH*0.9)
def mono_array_to_sound(array): array = np.clip(array, -1.0, +1.0) * _int16max # Mono sound, so copy the single channel to both left and right. array = np.array(zip(array, array)) return sndarray.make_sound(array.astype(np.int16))
def _make_tone(freq=800, volume=25000, length=1000): s = [ int(math.sin(n * freq * (6.28218 / 22050)) * volume) for n in range(int(length) * 11) ] return sndarray.make_sound(numpy.array([[val, val] for val in s]))
def as_sound(vector): scaled = vector * MAX_AMP/4 two_channel = np.array(np.transpose(np.asmatrix([[1], [1]]) * scaled), dtype=np.int16).copy(order='C') return sndarray.make_sound(array=two_channel)
def play(self, event=None): self.play_count += 1 pygame.mixer.music.stop() sound = make_sound(self.mix) pygame.mixer.Sound(sound).play()
#return harm_wave a = note_f(A) b = note_f(B) c = note_f(C) cl = note_f(C, leng*2) d = note_f(D) e = note_f(E) f = note_f(F) fs = note_f(FS) g = note_f(G) gl = note_f(G, leng*2) snd.make_sound(c).play() time.sleep(leng) snd.make_sound(c).play() time.sleep(leng) snd.make_sound(g).play() time.sleep(leng) snd.make_sound(g).play() time.sleep(leng) snd.make_sound(a).play() time.sleep(leng) snd.make_sound(a).play() time.sleep(leng) snd.make_sound(gl).play() time.sleep(leng*2) snd.make_sound(f).play() time.sleep(leng)