def sound_loop(): global people # constants samplerate = 44100 win_s = 2048 hop_s = win_s // 2 framesize = hop_s # set up audio input recorder = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE) #recorder = alsaaudio.PCM(type=PCM_CAPTURE, cardindex=1) recorder.setperiodsize(framesize) recorder.setrate(samplerate) #recorder.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE) recorder.setchannels(1) # create aubio pitch detection (first argument is method, "default" is # "yinfft", can also be "yin", "mcomb", fcomb", "schmitt"). pitcher = aubio.pitch("default", win_s, hop_s, samplerate) # set output unit (can be 'midi', 'cent', 'Hz', ...) pitcher.set_unit("Hz") # ignore frames under this level (dB) pitcher.set_silence(-40) count = 0 # main loop while True: # read data from audio input _, sdata = recorder.read() # convert data to aubio float samples samples = np.fromstring(sdata, dtype=np.int16) sample_test = np.array(samples, dtype=np.float32) freq = pitcher(sample_test)[0] # compute energy of current block energy = np.sum(sample_test**2) / len(sample_test) # do something with the results if freq > 130 and freq < 200 and energy > 300000: count = count + 1 if count > 1: count = 0 people = people + 1 print("{:10.4f} {:10.4f}".format(freq, energy))
def start(): global inp global audio global recorded while True: if inp == None: inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device) inp.setchannels(1) inp.setrate(16000) inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(500) audio = "" recorded = True os.system('mpg123 -q {}record_now.mp3'.format(path)) # recording(asyncronous) recording_thread = threading.Thread(target=async_recording) recording_thread.start() while recorded == True: l, data = inp.read() if l: audio += data recording_thread = None # os.system('arecord -d 3 -D {} {}recording.wav'.format(device,path)) os.system('mpg123 -q {}request_now.mp3'.format(path)) # call alexa rf = open(path + 'recording.wav', 'w') rf.write(audio) rf.close() inp = None # os.system('aplay {}recording.wav'.format(path)) alexa() time.sleep(10)
def listen_linux(frame_rate=44100, interval=0.1): mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="default") mic.setchannels(1) mic.setrate(44100) mic.setformat(alsaaudio.PCM_FORMAT_S16_LE) num_frames = int(round((interval / 2) * frame_rate)) mic.setperiodsize(num_frames) print("start...") in_packet = False packet = [] while True: l, data = mic.read() if not l: continue chunk = np.fromstring(data, dtype=np.int16) dom = dominant(frame_rate, chunk) print(dom) print(packet) if in_packet and match(dom, HANDSHAKE_END_HZ): byte_stream = extract_packet(packet) try: byte_stream = RSCodec(FEC_BYTES).decode(byte_stream) byte_stream = byte_stream.decode("utf-8") display(byte_stream) except ReedSolomonError as e: pass #print("{}: {}".format(e, byte_stream)) packet = [] in_packet = False elif in_packet: packet.append(dom) elif match(dom, HANDSHAKE_START_HZ): in_packet = True
def comm_to_user(message): FileDaRiprodurre = 'TEST.wav' # path del file da riprodurre f = wave.open(FileDaRiprodurre, 'rb') # file da riprodurre, aperto device = alsaaudio.PCM(device='default') # il device รจ quello di default # Setting del device device.setchannels(f.getnchannels()) device.setrate(f.getframerate()) device.setformat(alsaaudio.PCM_FORMAT_S16_LE) periodsize = f.getframerate( ) / 8 # dimensione dei chunck da riprodurre uno dopo l'altro! device.setperiodsize(f.getframerate() / 8) data = f.readframes(periodsize) # LEGGO DAL FILE AUDIO while data: device.write( data) # SCRIVO SUL DEVICE --> RIPRODUCO IL FILE PEZZO PER PEZZO data = f.readframes(periodsize) f.close() # chiudo il file audio
def _setThreshold(self): self.stream = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, 'default') self.stream.setchannels(self.channels) self.stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.stream.setrate(self.rate) self.stream.setperiodsize(self.size) for i in xrange(10): l, snddata = self.stream.read() try: self.low_threshold += self.getAmplitude(snddata) except TypeError: pass self.low_threshold = self.low_threshold/10 logging.info(self.low_threshold) return self.low_threshold
def start(): last = GPIO.input(button) while True: val = GPIO.input(button) GPIO.wait_for_edge(button, GPIO.FALLING) # we wait for the button to be pressed GPIO.output(lights[1], GPIO.HIGH) inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device) inp.setchannels(1) inp.setrate(16000) inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(500) audio = "" while(GPIO.input(button)==0): # we keep recording while the button is pressed l, data = inp.read() if l: audio += data rf = open(path+'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa()
def __init__(self): self.sample_rate = rospy.get_param("sample_rate") self.window_size = rospy.get_param("window_size") self.bit_depth = rospy.get_param("bit_depth") self.monitor_channels = rospy.get_param("monitor_channels") self.buffer_size = rospy.get_param("buffer_size") self.record_buffers = rospy.get_param("record_buffers") self.pcm = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK) self.pcm.setchannels(self.monitor_channels) if self.bit_depth == 16: self.pcm.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise Exception("Not supported bit depth") self.pcm.setrate(self.sample_rate) self.pcm.setperiodsize(self.buffer_size) rospy.Subscriber( rospy.get_param("subscribed_topic_names/audio_stream"), AudioData, self.callback) rospy.spin()
def play_wave_file(self, filename, repeat): self.stop_pcm = False sound_file = wave.open(filename, "rb") stream = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL) stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) stream.setperiodsize(self.FRAMES_IN_PERIOD) stream.setchannels(sound_file.getnchannels()) stream.setrate(sound_file.getframerate()) if repeat: while not self.stop_pcm: data = sound_file.readframes(self.FRAMES_IN_PERIOD) while data and not self.stop_pcm: stream.write(data) data = sound_file.readframes(self.FRAMES_IN_PERIOD) sound_file.rewind() else: data = sound_file.readframes(self.FRAMES_IN_PERIOD) while data and not self.stop_pcm: stream.write(data) data = sound_file.readframes(self.FRAMES_IN_PERIOD)
def play(path, callback): global wavfile, sample_rate, no_channels, matrix wavfile = wave.open(path, "r") sample_rate = wavfile.getframerate() no_channels = wavfile.getnchannels() output = aa.PCM(aa.PCM_PLAYBACK, aa.PCM_NORMAL) output.setchannels(no_channels) output.setrate(sample_rate) output.setformat(aa.PCM_FORMAT_S16_LE) output.setperiodsize(chunk) data = wavfile.readframes(chunk) while data != '': output.write(data) matrix = calculate_levels(data, chunk, sample_rate, matrix) pattern = ''.join(str(e) for e in matrix.tolist()) print pattern if callback != None: callback([pattern]) data = wavfile.readframes(chunk)
def doring(self): if self.ringfile is not None: self.ringfile.rewind() else: self.ringfile = wave.open(self.config["soundfiles"]["ringtone"], 'rb') self.device = alsaaudio.PCM(card="plughw:1,0") self.device.setchannels(self.ringfile.getnchannels()) self.device.setrate(self.ringfile.getframerate()) self.device.setperiodsize(320) while self.shouldring: data = self.ringfile.readframes(320) while data: self.device.write(data) data = self.ringfile.readframes(320) self.ringfile.rewind() time.sleep(2) if time.time() - 60 > self.ringstart: self.stop()
def play(f): device = alsaaudio.PCM() device.setchannels(f.getnchannels()) device.setrate(f.getframerate()) if f.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) # Otherwise we assume signed data, little endian elif f.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) elif f.getsampwidth() == 3: device.setformat(alsaaudio.PCM_FORMAT_S24_LE) elif f.getsampwidth() == 4: device.setformat(alsaaudio.PCM_FORMAT_S32_LE) else: raise ValueError('Unsupported format') device.setperiodsize(320) data = f.readframes(320) while data: # Read data from stdin device.write(data) data = f.readframes(320)
def play(file_name): import alsaaudio f = open(file_name, 'rb') # Open the device in playback mode. out = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK) # Set attributes: Mono, 44100 Hz, 16 bit little endian frames out.setchannels(1) out.setrate(16000) out.setformat(alsaaudio.PCM_FORMAT_S16_LE) # The period size controls the internal number of frames per period. # The significance of this parameter is documented in the ALSA api. out.setperiodsize(512) #160 # Read data from stdin data = f.read(512) #320 while data: out.write(data) data = f.read(512)
def init(etc_object, AOUT_JACK): global aout_jack, inp, client, etc, trig_this_time, trig_last_time, sin aout_jack = AOUT_JACK etc = etc_object if aout_jack: jack_connected = False # set up jack for sound in client = jack.Client("eyesy_jack_client", servername="default") client.inports.register('input_1') client.inports.register('input_2') client.blocksize = 512 client.activate() while not (jack_connected): try: client.connect('crone:output_1', 'eyesy_jack_client:input_1') client.connect('crone:output_2', 'eyesy_jack_client:input_2') jack_connected = True except: pass time.sleep(1) inp = [ client.get_port_by_name('eyesy_jack_client:input_1'), client.get_port_by_name('eyesy_jack_client:input_2') ] else: #setup alsa for sound in inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK) inp.setchannels(2) inp.setrate( 48000 ) # set to appropriate amount for soundcard .. OR 44100 / 48000 inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(1024) # OR 1024 trig_last_time = time.time() trig_this_time = time.time() for i in range(0, 100): sin[i] = int(math.sin(2 * 3.1459 * i / 100) * 32700)
def start_old(): global audioplaying, p inp = None # last = GPIO.input(button) last = gpio.input(button) print("{}Ready to Record.{}".format(bcolors.OKBLUE, bcolors.ENDC)) while True: # val = GPIO.input(button) val = gpio.input(button) if val != last: last = val if val == 1 and recorded == True: print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC)) rf = open(path + 'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa_speech_recognizer() elif val == 0: # GPIO.output(rec_light, GPIO.HIGH) gpio.output(rec_light, gpio.HIGH) print("{}Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC)) inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device) inp.setchannels(1) inp.setrate(16000) inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(500) audio = "" if audioplaying: p.stop() l, data = inp.read() if l: audio += data recorded = True elif val == 0: l, data = inp.read() if l: audio += data
def main(self): out = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK) out.setchannels(self.channels) out.setrate(self.rate) out.setformat(self.format) out.setperiodsize(self.periodsize) loops = self.maxloops shutdown = False while not shutdown or self.dataReady("inbox"): loops -= 1 if self.dataReady("inbox"): data = self.recv("inbox") out.write(data) if self.dataReady("control"): data = self.recv("control") if isinstance(data, Axon.Ipc.producerFinished): self.send(data, "signal") shutdown = True time.sleep(self.delay) print "Shutdown :-)"
def play_silence(): """In order to make alsa see the mixers, play some silent audio. Otherwise 'Unable to find mixer control alsacontrol-output-mute' will be thrown at the start. """ logger.debug('Trying to play sound to make the output mixers visible') try: pcm = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, channels=1, periodsize=32, device='default') data = b'\x00' * 32 pcm.write(data) except alsaaudio.ALSAAudioError as error: error = str(error) logger.error(error) if 'resource busy' in error: logger.error( 'Your specified output is currently busy, is jack using it?') logger.error('Could not initialize output mixer, ' 'try setting a different device.')
def capture_guitar_sound(): global shared_buf_signal_data global producer_count global consumer_count device = 'hw:1' # device = 'default' inp = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NONBLOCK, device=device) inp.setchannels(1) inp.setrate(sampling_rate) inp.setformat(aa.PCM_FORMAT_S16_LE) # For our purposes, it is suficcient to know that reads from the device # will return this many frames. Each frame being 2 bytes long. # This means that the reads below will return either 320 bytes of data # or 0 bytes of data. The latter is possible because we are in nonblocking # mode. inp.setperiodsize(int(period_size)) # Open a file to test data integrity # f = open("/home/andrei/f/licenta/guitar-signal-process/test.wav", 'wb') while 1: l, data = inp.read() # print("--- abs time %s seconds ---" % (time.time() - abs_start_time)) if l > 0: # append data if any # f.write(data) queue.append(data) # print("size: ", l) # print("produced: ", producer_count, "consumed", consumer_count) elif l < 0: print("data lost!")
def __init__(self): rospy.on_shutdown(self.shutdown) # Create a publisher for the grammar data and raw audio self.pub_grammar = rospy.Publisher("grammar_data", String, queue_size=10) self.pub_audio = rospy.Publisher("raw_audio", String, queue_size=10) self.alert_pub = rospy.Publisher('patient_monitor/alerts', Alert, queue_size=10) self.alert_client(1) #self.alert_client(2) #self.alert_client(3) # Subscribe to grammar data output rospy.Subscriber("grammar_data", String, self.parse_results) # Set language model and dictionary self.class_lm = 'corpus/final.lm' self.dict = 'corpus/final.dic' # Used in process_audio (from asr_test.py) self.in_speech_bf = False # Set this file from "/usr/share/pocketsphinx/model/hmm/en_US/hub4wsj_sc_8k" self.hmm = 'corpus/hmm' # Intializing robot API self.lights = robot_api.Lights() self.expressions = robot_api.Expressions() self.sound_source = robot_api.SoundSource('Luci') # Initialize alsa audio PCM: (Using 16000Hz, 16 Bit Encoding, 1 Channel) self.inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK) self.inp.setchannels(1) self.inp.setrate(16000) self.inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.inp.setperiodsize(160) start_thread = Thread(target=self._start) start_thread.start()
def __init__(self): # Open the device in nonblocking capture mode. The last argument could # just as well have been zero for blocking mode. Then we could have # left out the sleep call in the bottom of the loop device = 'rate16000Hz' self.inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device=device) # Set attributes: Mono, 16000 Hz, 16 bit little endian samples self.inp.setchannels(1) self.inp.setrate(16000) self.inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) # The period size controls the internal number of frames per period. # The significance of this parameter is documented in the ALSA api. # For our purposes, it is suficcient to know that reads from the device # will return this many frames. Each frame being 2 bytes long. # This means that the reads below will return either 320 bytes of data # or 0 bytes of data. The latter is possible because we are in nonblocking # mode. self.inp.setperiodsize(1024)
def __init__(self): self.name = "development_1" self.server = "localhost" self.topic = "SOUNDPRESENCE" self.notifyDifference = 0.1 self.sound_level = 0 self.sound_level_min = 1000 self.sound_level_max = 0 self.client = mqtt.Client(self.name) self.client.connect(self.server, 1883, 60) self.client.publish(self.getTopic("ONLINE")) self.client.loop_start() self.inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL) self.inp.setchannels(1) self.inp.setrate(8000) self.inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.inp.setperiodsize(128) self.collect_samples()
def __init__(self): mycard = "plug:leftrecord" #mycard = "plug:mixin" #mycard = "Loopback PCM" self.inp = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE, mode=alsaaudio.PCM_NORMAL, card=mycard) self.inp.setchannels(self.CHANNELS) self.inp.setrate(self.RATE) self.inp.setformat(self.INFORMAT2) self.inp.setperiodsize(self.FRAMESIZE) self.l = 0 self.data_ = None self.new_data = False self.dtime = self.FRAMESIZE / self.RATE self.cards = alsaaudio.cards() self.mixers = alsaaudio.mixers() #print self.mixers self.mixMaster = alsaaudio.Mixer('Master') #check ik in self.mixers self.thread = Threaded(self.read)
def begin_stream(listener): global streaming fmt = alsaaudio.PCM_FORMAT_S8 rate = 8000 # period = 1024 card = alsaaudio.cards()[1] stream = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, card) stream.setchannels(1) stream.setrate(rate) stream.setformat(fmt) # stream.setperiodsize(period) streaming = True while streaming: start_time = time.time() l, data = stream.read() if l: decoded = numpy.fromstring(data, 'int8') decoded = numpy.nan_to_num(decoded) listener(decoded.tolist(), rate, 8, start_time)
def load(self, path): """ Loads a uncompressed music file into the object. This can be called as many times as you would like during the lifetime of the object, as long as the previous file has finished playing. """ logger.debug("loading player with sound: %s" % path) p = os.path.abspath(path) self.playing = False self._w = wave.open(p) self._player = aa.PCM(aa.PCM_PLAYBACK, aa.PCM_NORMAL) self._player.setchannels(self._w.getnchannels()) self._player.setrate(self._w.getframerate()) self._player.setformat(aa.PCM_FORMAT_S16_LE) self._player.setperiodsize(self._periodsize) self._t = threading.Thread(target=self._run)
def set_audio_source(self): stream_reader = None outq = None if cm.lightshow.mode == 'audio-in': # Open the input stream from default input device self.streaming = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NORMAL, cm.lightshow.audio_in_card) self.streaming.setchannels(self.num_channels) self.streaming.setformat(aa.PCM_FORMAT_S16_LE) # Expose in config if needed self.streaming.setrate(self.sample_rate) self.streaming.setperiodsize(self.chunk_size) stream_reader = lambda: self.streaming.read()[-1] elif cm.lightshow.mode == 'stream-in': outq = Queue() if cm.lightshow.use_fifo: self.streaming = subprocess.Popen(cm.lightshow.stream_command_string, stdin=subprocess.PIPE, stdout=subprocess.PIPE, preexec_fn=os.setsid) io = os.open(cm.lightshow.fifo, os.O_RDONLY | os.O_NONBLOCK) stream_reader = lambda: os.read(io, self.chunk_size) outthr = Thread(target=self.enqueue_output, args=(self.streaming.stdout, outq)) else: # Open the input stream from command string self.streaming = subprocess.Popen(cm.lightshow.stream_command_string, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stream_reader = lambda: self.streaming.stdout.read(self.chunk_size) outthr = Thread(target=self.enqueue_output, args=(self.streaming.stderr, outq)) outthr.daemon = True outthr.start() return stream_reader,outq
def __init__(self): logging.info("starting up") # Open the device in nonblocking capture mode. The last argument could # just as well have been zero for blocking mode. Then we could have # left out the sleep call in the bottom of the loop self.inp = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, device='default') # Set attributes: Mono, 8000 Hz, 16 bit little endian samples self.inp.setchannels(1) self.inp.setrate(8000) self.inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) # The period size controls the internal number of frames per period. # The significance of this parameter is documented in the ALSA api. # For our purposes, it is suficcient to know that reads from the device # will return this many frames. Each frame being 2 bytes long. # This means that the reads below will return either 320 bytes of data # or 0 bytes of data. The latter is possible because we are in nonblocking # mode. # Higher than 1600 appears to add a delay. # Use a multiple of 8 self.inp.setperiodsize(160)
def _openStream(self): self.stream = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, 'default') self.stream.setchannels(self.channels) self.stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.stream.setrate(self.rate) self.stream.setperiodsize(882) self.nothing = 0 self.something = 0 while 1: #time.sleep(.01) l, snddata = self.stream.read() #logging.info(self.getFrequency(snddata)) if l: #logging.info(l) if self.getAmplitude(snddata) >= self.low_threshold * 1.3: #logging.info(self.getFrequency(snddata)) self.something += 1 self.nothing = 0 self.raw_data.put(snddata) #logging.info('live long') if self.something >= 1000: self._setThreshold() self.something = 0 self.nothing = 0 elif self.getAmplitude(snddata) <= self.low_threshold * 0.7: self.nothing += 1 self.something = 0 if self.nothing >= 500: self._setThreshold() self.nothing = 0 self.something = 0
def init(etc_object, AOUT_NORNS): global aout_norns, inp, client, etc, trig_this_time, trig_last_time, sin aout_norns = AOUT_NORNS etc = etc_object if aout_norns: norns_connected = False # set up jack for sound in client = jack.Client("fates_jack_client", servername="default") client.inports.register('input_1') client.inports.register('input_2') client.blocksize = 512 client.activate() while not (norns_connected): try: client.connect('crone:output_1', 'fates_jack_client:input_1') client.connect('crone:output_2', 'fates_jack_client:input_2') norns_connected = True except: pass time.sleep(1) inp = [ client.get_port_by_name('fates_jack_client:input_1'), client.get_port_by_name('fates_jack_client:input_2') ] else: #setup alsa for sound in inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK) inp.setchannels(2) inp.setrate( 44100) # Original value of 11025 was giving error.. OR 44100 inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(1024) # OR 1024 trig_last_time = time.time() trig_this_time = time.time() for i in range(0, 100): sin[i] = int(math.sin(2 * 3.1459 * i / 100) * 32700)
def __init__(self, relay): self.inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK) # Set attributes: Mono, 8000 Hz, 16 bit little endian samples self.inp.setchannels(1) self.inp.setrate(8000) self.inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) # The period size controls the internal number of frames per period. # Reads from the device will return this many frames. Each frame being 2 bytes long. # This means that the reads below will return either 320 bytes of data # or 0 bytes of data. The latter is possible because we are in nonblocking # mode. self.inp.setperiodsize(160) # Relay object self.relay = relay # Flag: switch only once per peak self.hold = False self.thread = threading.Thread(target=self.__listen)
def main(argv): recorder = alsaaudio.PCM(alsaaudio.PCM_CAPTURE) recorder.setchannels(1) recorder.setrate(44100) recorder.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE) recorder.setperiodsize(441) times = numpy.linspace(0, 1, 44100) do4 = numpy.sin(2*numpy.pi*261.63*times) do_s4 = numpy.sin(2*numpy.pi*277.18*times) re4 = numpy.sin(2*numpy.pi*293.66*times) re_s4 = numpy.sin(2*numpy.pi*311.13*times) mi4 = numpy.sin(2*numpy.pi*329.63*times) fa4 = numpy.sin(2*numpy.pi*349.23*times) fa_s4 = numpy.sin(2*numpy.pi*369.99*times) sol4 = numpy.sin(2*numpy.pi*392.00*times) sol_s4 = numpy.sin(2*numpy.pi*415.30*times) la4 = numpy.sin(2*numpy.pi*440.*times) la_s4 = numpy.sin(2*numpy.pi*466.16*times) si4 = numpy.sin(2*numpy.pi*493.88*times) notes = [do4, do_s4, re4, re_s4, mi4, fa4, fa_s4, sol4, sol_s4, la4, la_s4, si4] energy_notes = [0,0,0,0,0,0,0,0,0,0,0,0] signal_sound = [] while True: for sample in range(0,10): l, data = recorder.read() buffer = list(struct.unpack('f'*441,data)) signal_sound = signal_sound + buffer for note in range(0, 12): energy_notes[note] = numpy.sum(numpy.power(numpy.convolve(signal_sound, notes[note]), 2)) print "max is: " print energy_notes.index(numpy.max(energy_notes)) signal_sound = [] print "begginnig other"
def record(min_duration=1, # Record at least this many seconds max_duration=8, # But no more than this many seconds max_silence=1, # Stop recording after silence this long silence_threshold=DEFAULT_SILENCE_THRESHOLD, # Silence is < this silence_factor=0.25): # Or, less than this fraction of max chunk_duration = 1.0/16 # record in batches this many seconds long chunk_size = int(SAMPLES_PER_SECOND * chunk_duration) mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, card=ALSA_MICROPHONE) mic.setchannels(1) mic.setrate(SAMPLES_PER_SECOND) mic.setformat(FORMAT) mic.setperiodsize(chunk_size) recording = Recording(silence_factor=silence_factor, silence_threshold=silence_threshold) while True: _, chunk = mic.read() chunkarray = array('h', chunk) for sample in chunkarray: recording.add(sample) # How long is the recording now? duration = recording.duration() # If we've reached the maximum time, stop recording if duration >= max_duration: break # If we've recorded for at least the minimum time and have # recorded at least the maximum silence, then stop recording. if recording.duration() >= min_duration and \ recording.trailing_silence() >= max_silence: break return recording.get_audible_samples()