def send_btn_clicked(self): self.OK = True if 'Normal' == self.speedBtn.text(): samplerate = 9600 elif 'Slow' == self.speedBtn.text(): samplerate = 7000 elif 'Fast' == self.speedBtn.text(): samplerate = 19200 sounddevice.playrec(self.recording, blocking=True,\ samplerate=samplerate, channels=1) self.close()
def playrec_sw(self, function, frec, amp=0.5, long=1): "pone una función serrucho o triangular y la graba al mismo tiempo. La salida de esta función es: un gráfico que muestra la señal que mandó y la que midió y el array correspondiente a la medición. " a = self.sawtooth(function, frec, amp=amp, long=long) myrec = sd.playrec(a, self.fs, channels=2) sd.wait() plt.plot(myrec) #,plt.plot(self.serrucho(Vin,Vend,long=long,n=n)) return myrec
def play_and_rec_directory(input_path, output_path): """Play each .wav file specified in the input directory and record the output simultaneously Parameters: input_path: Location of input .wav files to be transmitted output_path: Location for output .wav files that are recorded with output_ appended to the start of the string Returns None """ # DAM_MRR - output keyword and hard coded string, come back and visit logging.info("Enter: play_and_rec_directory") for dirpath, dirnames, filenames in os.walk(input_path): for file_ in filenames: if WAV not in file_: logging.info( "A non .wav file was encountered and thus not used:" " {}".format(file_)) continue print("processing... ", file_) rate, data = wf.read(os.path.join(dirpath, file_)) output_array = sd.playrec(data, rate, channels=1, blocking=True) sd.wait() output_location = output_path + "\\" + str("output_" + file_) print(output_location, "\nSuccess...\n") wf.write(output_location, int(rate), output_array) logging.info("Exit: play_and_rec_directory")
def transmissao(duracao=2): tempo, sinalao = geraNum(number=numero(), duration=duracao) myrecording = sd.playrec(sinalao, fs, channels=1) sd.wait() plt.plot(sinalao[:1000]) plt.title('Sinal do numero até 1000') plt.show()
def measure_tf2(fs=8000, T=3, fmin=20, fmax=500): # sweep Tr = 0.1 t, win = window_signal(fs, T, Tr=0.1) N = len(t) x = np.zeros(N) y = np.zeros(N) x = win * ss.chirp(t, fmin, T - 6 * Tr, fmax) f = np.fft.rfftfreq(N, 1 / fs) #%% LOG DATA print('Sweep: {} to {} (Hz)'.format(fmin, fmax)) y = sd.playrec(x, samplerate=fs, channels=1, blocking=True) X = np.fft.rfft(x) Y = np.fft.rfft(y[:, 0]) G2 = Y / X settings = dvma.MySettings(fs=fs, channels=1) tfdata = dvma.TfData(f, G2, None, settings, test_name='sweep') plot_tf(tfdata) return tfdata
def barrido_frecuencia_onda(self, frec_min, frec_max, pasos=15, amp=None, long=10): "Genera un vector de frecuencias entre la mínima y la máxima, con los pasos especificados. Manda funcines senoidales de esa frencuencia y graba la respuesta. Devuelve (por ahora) el vector de frecuencias y un gráfico que muestra la amplitud máxima registrada (puede mejorarse como la obtiene) en función de la frecuencia.CALCULAR LÍMITE TEORICO" frecs = np.logspace(np.log10(frec_min), np.log10(frec_max), num=pasos) output = np.zeros([pasos, 5]) for i in range(len(frecs)): frec = frecs[i] output[i, 0] = frecs[ i] # primer dato freec, segundo pot de entrada, tercero y cuarto pot de salida rec = sd.playrec(self.crearOnda(frec, amp=amp, long=long), self.fs, channels=2) sd.wait() channels = [0, 1] for channel in channels: output[i, 3 + channel] = self.calculo_potencia(rec[:, channel]) output[i, 1 + channel] = self.calculo_potencia( self.crearOnda(frec, amp=amp, long=long)) plt.plot(output[:, 0], output[:, 1], output[:, 0], output[:, 2], output[:, 0], output[:, 3], output[:, 0], output[:, 4], '*') return output
def play_and_rec(pb_wav_fname, rec_wav_fname, normalise=True, rm_latency=True, show_plots=False): """ Function plays and records simultaneously an audio file and stores the result in the same format as an input file. Output_dir is created if it does not exist just before writing the output file. :param pb_wav_fname: input wavefile path :param rec_wav_fname: output wavefile path :param normalise: (default True) applies amplitude normalisation to the input samples :param rm_latency: (default True) removes latency introduced during recording based on simple lookup for :param show_plots: (default False) plots the Original(playback) and Recorded signals :return: tuple with original samples, recorded samples and sampling rate """ (fs, pb_samples) = read(pb_wav_fname) if normalise: pb_samples = pb_samples / (0.8 * pb_samples.max()) # normalise input pb_samples_padded = np.pad(pb_samples, (0, round(0.5 * fs)), mode='constant', constant_values=0) rec_samples = sd.playrec(pb_samples_padded, fs, channels=1, blocking=True) if rm_latency: eps = 3 * 1.0 / (2**15) # assumes 16-bit WAV resolution ind = np.argmax(abs(rec_samples) > eps) rec_samples = rec_samples[ind:] # removes latency output_path = os.path.dirname(rec_wav_fname) if not os.path.isdir(output_path): os.makedirs(output_path) write(rec_wav_fname, fs, rec_samples) if show_plots: plot_signal(pb_samples, fs, 'Original', 1) plot_signal(rec_samples, fs, 'Recorded', 2) return rec_samples, pb_samples, fs
def playrec_tone(frecuencia, duracion, amplitud=0.5, fs=200000): """ Emite un tono y lo graba. """ sd.default.samplerate = fs # frecuencia de muestreo sd.default.channels = 2,2 # por las dos salidas de audio cantidad_de_periodos = duracion*frecuencia puntos_por_periodo = int(fs/frecuencia) puntos_totales = puntos_por_periodo*cantidad_de_periodos tiempo = np.linspace(0, duracion, puntos_totales) # interpola puntos_totales entre 0 y duracion data = amplitud*np.sin(2*np.pi*frecuencia*tiempo) # funcion que genera los datos para el ono grabacion = sd.playrec(data, blocking=True) # graba los datos de entrada (line in) plt.subplot(2,1,1) plt.plot(tiempo, data,'b.--') # grafica datos emitidos plt.xlim([0.524, 0.525]) plt.subplot(2,1,2) plt.plot(tiempo, grabacion,'r.--') # grafica datos grabados (line in o input) plt.xlim([0.524, 0.525]) return tiempo, data, grabacion
def playrec(signals, **kwargs): import sounddevice as sd fs = kwargs.get("fs", 96) channels = kwargs.get("channels", 2) blocking = kwargs.get("blocking", True) _fs = fs * 1000 return sd.playrec(signals, _fs, channels=channels, blocking=blocking)
def playback_record(self, fs, duration, amplitude, frequency, phase, waveform, loop): self.fs = fs self.duration = duration self.amplitude = amplitude self.frequency = frequency self.phase = phase self.waveform = waveform self.loop = loop # Set the input numpy.array to reproduce time = np.linspace(start=0, stop=duration, num=duration * fs) sound = None if waveform == 'SIN': sound = amplitude * np.sin(2 * np.pi * frequency * time + phase) elif waveform == 'SQR': sound = amplitude * sg.square(2 * np.pi * frequency * time + phase, 0.5) elif waveform == 'RAMP': sound = amplitude * sg.sawtooth( 2 * np.pi * frequency * time + phase, 0.5) elif waveform == 'PULSE': sound = amplitude * sg.unit_impulse(shape=np.size(time), idx='mid') recording = sd.playrec( data=sound, samplerate=fs, blocking=False ) # If False, return immediately (but continue playrec in the background). return time, sound, recording
def sound_recorder(self, record_only=True): recording = sd.rec(int(self.seconds * self.fs), samplerate=self.fs, channels=1) sd.wait() self.lock.acquire() self.user_tracks_in_queue.append(recording) self.lock.release() while self.running: if not self.muted: if self.participant_tracks_in_queue: # print(time.time(), 'playing') current_playing = self.participant_tracks_in_queue.pop(0) self.state = 1 recording = sd.playrec(current_playing, samplerate=self.fs, channels=1) sd.wait() # print(time.time(), 'finished playing') elif self.total_tracks == 0 or record_only: # print(time.time(), 'recording') self.state = 2 recording = sd.rec(int(self.seconds * self.fs), samplerate=self.fs, channels=1) sd.wait() # print(time.time(), 'finished recording') self.lock.acquire() self.user_tracks_in_queue.append(recording) self.lock.release() else: self.user_tracks_in_queue = []
def measure(self, waveform_string): sd.default.device = "Scarlett 2i2 USB: Audio" sd.default.blocksize = 512 sd.default.samplerate = self.sample_rate_Hz sd.default.channels = 1 x = np.array(self.get_waveform_data(waveform_string), dtype=float) y = sd.playrec(np.hstack([ x, x, x, np.zeros(int(0.2 * self.sample_rate_Hz)), ])) sd.wait() y = y.T[0] y = y[len(y)//2:] # Locate x in y R = abs(signal.correlate(y, x, "valid")) start = np.argmax(R) y = y[start:start+len(x)] # Store results self.x = x self.y = y
def playRec(audio, fs = 44100): ''' Plays an audio input and simultaneously records the default microphone through your default system audio drivers, using the Sounddevice library. Parameters ---------- audio : ndarray Numpy array containing the input signal. fs : int Sampling frequency. Returns ------- record : ndarray Numpy array containing the mono normalized signal recorded from the micrpohone. ''' record = sd.playrec(audio, samplerate = fs, channels = 1) sd.wait() record = record/max(abs(record)) sf.write("./static/audio/record.wav", record, fs) return record
def test_frequency(freq, sr, config): ''' test a single frequency :param freq: frequency to test :param sr: sample rate :param config: config dict :return: amplitude, rms ''' n_waves = config.get('n_waves', 20) drop_begin = config.get('drop_begin', 0.0) drop_end = config.get('drop_end', 0.0) # generate test signal sgn_len = n_waves / freq + drop_begin + drop_end test_signal = generate_sine(freq, sgn_len, sr) # play/rec rec_signal = sd.playrec(test_signal, samplerate=sr, channels=1) # block execution sd.wait() # do the cropping rec_signal = crop_signal(rec_signal, drop_begin, drop_end, sr) # filtering. do some normalization due to that #rec_signal = bandpass(rec_signal, freq, sr) # return values ampl = np.max(np.abs(rec_signal)) rms = np.mean(np.square(rec_signal)) return ampl, rms
def run_sweep_measurement(self): cfg = { **self._config, **self._config['sweep'], **self._config['measurement'], **self._config['sounddevice']} if not self._sweep: self._sweep = SyncSweep( startfreq=cfg['startfreq'], stopfreq=cfg['stopfreq'], durationappr=cfg['durationappr'], samplerate=cfg['samplerate'], ) sweep_playback_signal = self._sweep.get_windowed_signal( left=cfg['flanksamples'], right=cfg['flanksamples'], pausestart=cfg['pausestart'], pausestop=cfg['pausestop'], amplitude=10**(cfg['sweep']['level_dbfs']/20)) measured_sweep = _sd.playrec( sweep_playback_signal, samplerate=cfg['samplerate'], device=cfg['device'], input_mapping=cfg['channelmap_input'], output_mapping=cfg['channelmap_output'], blocking=True) return sweep_playback_signal, measured_sweep
def test_soundcard(i="default",o="default", fs=fs, ch=2): dummy1sec = zeros(int(fs)) print( 'Trying:' ) print(f' {sd.query_devices(i, kind="input" )["name"]}') print(f' {sd.query_devices(o, kind="output")["name"]}') try: sd.default.device = i, o except Exception as e: print( f'(!) Error accesing devices [{i},{o}]: {e}' ) return e try: chk_rec = sd.check_input_settings (i, channels=ch, samplerate=float(fs)) chk_pb = sd.check_output_settings(o, channels=ch, samplerate=float(fs)) print( f'Sound card parameters OK' ) except Exception as e: print( f'(!) Sound card [{i},{o}] ERROR: {e}' ) return e try: dummy = sd.playrec(dummy1sec, samplerate=fs, channels=ch) print( 'Sound device settings are supported' ) except Exception as e: print( f'(!) FAILED to playback and recording on selected device: {e}' ) return e return 'ok'
def test4(txt='oopsie daisy :O'): start_time = time.time() text = encrypt(strin) #print("encrypted to " + text) #print("encryption len: " + str(len(text))) w = make_sound(text, 0.05, 1) w = append_waves(sine_wave(0, 1), make_header(),w,make_footer(), sine_wave(0, 1)) myrec = sd.playrec(w, 44100, 1) myrec = np.reshape(myrec, [myrec.size]) sd.wait() #plot_spec(myrec) decrypt = demodulate(myrec) if len(decrypt) != len(text): print("Off by one") decrypt = demodulate(myrec, True, 1100) decode(decrypt) # filtered = [] # for i in range(len(decrypt)//4): # if 4*i + 4 < len(decrypt): # filtered.append(maxfreq(decrypt[4*i:4*i + 4])) # else: # filtered.append(maxfreq(decrypt[4*i:])) # print(filtered, len(filtered)) # print(decode(filtered)) run_time = (time.time() - start_time) print("---- %s seconds ----" % run_time) print("Bit rate: %s" % str(8*len(strin) / run_time)) print("Physical Bit rate: %s" % str(8*len(text) / run_time)) print(decode(decrypt)) return myrec
def conduct_measurement(self, playback=False): devices = self.get_audio_devices() try: if playback: # simultaneous playback and recording (only possible when both input and output device are operated by # the same computer recording = sd.playrec(self.sweep, samplerate=self.fs, device=devices, channels=4, blocking=True) else: # if no simultaneous playback is possible, allow some additional time (e.g. 2 seconds) in case the # server connection is very slowly recording_length = len(self.sweep) + 2 * self.fs recording = sd.rec(recording_length, samplerate=self.fs, device=devices[0], channels=4, blocking=True) except ValueError as e: self.logger.error( 'The measurement was not successful, because there was a problem with the sound device. ' 'Maybe check the sound-device names with sd.query_devices() and adjust them in the ' 'measurement parameters.') raise SweepMeasurementError( 'The measurement was not successful, because there was a problem with the ' 'sound device. Maybe check the sound-device names with sd.query_devices() and ' 'adjust them in the measurement parameters.') from e self.recording2rirs(recording)
def playrec_serr(self, Vin, Vend, long=1 / 440, n=440): "pone una función serrucho y la graba al mismo tiempo. La salida de esta función es: un gráfico que muestra la señal que mandó y la que midió y el array correspondiente a la medición. " a = self.serrucho(Vin, Vend, long=long, n=n) myrec = sd.playrec(a, self.fs, channels=2) sd.wait() plt.plot(myrec) #,plt.plot(self.serrucho(Vin,Vend,long=long,n=n)) return myrec
def playrec(self): import sounddevice as sd sd.default.channels = 2 sd.default.samplerate = self.sample_rate rec = sd.playrec(self.play_data, self.sample_rate) sd.wait() return rec.T
def record_noise(fs, noise_duration,detection_duration, description='', save_wav=True): # first incorporate delay between speaker and microphone detection_duration = detection_duration+delay_speaker_mic if description != '': description = '_'+description.replace(" ", "_") noise_template = np.random.normal(0,1,size=round(noise_duration*fs)) zeros_padded_front = 0 zeros_padded_back = round(detection_duration*fs)-zeros_padded_front-round(noise_duration*fs) noise_zero_padded = np.concatenate([np.zeros(zeros_padded_front), noise_template, np.zeros(zeros_padded_back)]) # adjust the today datetime variable, the result should be global!!! global today today = datetime.today() date_folder = create_date_folder(today) recorded_noise = sounddevice.playrec(noise_zero_padded, samplerate = fs, channels = nb_channels)#, blocking = True) time.sleep(2*len(noise_zero_padded)/fs) recorded_noise = recorded_noise[round(delay_speaker_mic*fs):,:] if save_wav: wav_specifications = format_nb_digits(round(noise_duration*1000),2) + 'ms_whitenoise' wav_name = date_folder + get_date_based_filename(today) + '_' + wav_specifications + description wavfile.write(wav_name + '.wav', fs, recorded_noise) return [noise_template, recorded_noise]
def test_fft(freq, sr, fft_len=4096): ''' generate a test signal of single sine wave, record the output and compute fft of the recorded signal. returns two vectors: first one contains frequencies, the second amplitudes :param freq: test frequency :param sr: sample rate :param fft_len: fft length :return: frequency, amplitude ''' n_burnin = sr // 2 sgn_len = sr // 2 # generate test wave for the given frequency sgn = generate_sine(freq, n_burnin + sgn_len, sr) # play & record rec = sd.playrec(sgn, samplerate=sr, channels=1)[:, 0] sd.wait() # crop rec = rec[n_burnin:n_burnin + fft_len] # do the fft fr = fft_freqs(len(rec), sr) am = get_fft(rec, sr) am = np.abs(am) return fr, am
def record_sweep(fs, f_start, f_end, chirp_duration,detection_duration, description='', save_wav=True): # first incorporate delay between speaker and microphone add_sample_delay = 100 + round(chirp_duration*fs) + offset detection_duration = detection_duration+delay_speaker_mic+ round(add_sample_delay/fs) if description != '': description = '_'+description.replace(" ", "_") t_template = np.linspace(0, chirp_duration, round(chirp_duration*fs)) chirp_template = chirp(t_template, f0=f_start, f1=f_end, t1=chirp_duration, method='linear') zeros_padded_front = 0 zeros_padded_back = round(detection_duration*fs)-zeros_padded_front-round(chirp_duration*fs) chirp_zero_padded = np.concatenate([np.zeros(zeros_padded_front), chirp_template, np.zeros(zeros_padded_back)]) global today today = datetime.today() date_folder = create_date_folder(today) recorded_chirp = sounddevice.playrec(chirp_zero_padded, samplerate = fs, channels = nb_channels)#, blocking = True) #sounddevice.wait() time.sleep(3*len(chirp_zero_padded)/fs) # cut off delay and length of emitted signal recorded_chirp = recorded_chirp[(round(delay_speaker_mic*fs) + add_sample_delay):,:] if save_wav: wav_specifications = format_nb_digits(round(chirp_duration*1000),2) + 'ms_' + str(round(f_start/1000)) + 'k_' + str(round(f_end/1000)) + 'kHz_chirp' wav_name = date_folder + get_date_based_filename(today) + '_' + wav_specifications + description wavfile.write(wav_name + '.wav', fs, recorded_chirp) return [chirp_template, recorded_chirp]
def measure(f_band, f_averaging=80): if f_band == '125': [f_sample_rate, f_data] = scipy.io.wavfile.read("4_125_Hz.wav") elif f_band == '250': [f_sample_rate, f_data] = scipy.io.wavfile.read("4_250_Hz.wav") elif f_band == '500': [f_sample_rate, f_data] = scipy.io.wavfile.read("4_500_Hz.wav") elif f_band == '1000': [f_sample_rate, f_data] = scipy.io.wavfile.read("4_1000_Hz.wav") elif f_band == '2000': [f_sample_rate, f_data] = scipy.io.wavfile.read("4_2000_Hz.wav") elif f_band == '4000': [f_sample_rate, f_data] = scipy.io.wavfile.read("4_4000_Hz.wav") elif f_band == '8000': [f_sample_rate, f_data] = scipy.io.wavfile.read("4_8000_Hz.wav") elif f_band == 'full': [f_sample_rate, f_data] = scipy.io.wavfile.read("4_full_range.wav") else: print("No band selected. Select the right band to measure.") return 1 f_measurement = sd.playrec(f_data, f_sample_rate, 1, blocking=True) sd.wait() [f_energy, f_division] = energy_decay(f_measurement, f_sample_rate, f_averaging) return f_energy, f_division
def single_measurement(self, type=None): # little workaround of a problem with using ASIO from multiple threads # https://stackoverflow.com/questions/39858212/python-sounddevice-play-on-threads default_device = sd.query_devices(sd.default.device[0]) default_api = sd.query_hostapis(default_device['hostapi']) if default_api['name'] == 'ASIO': sd._terminate() sd._initialize() self.recorded_sweep_l = [] self.recorded_sweep_r = [] self.feedback_loop = [] if type is 'hpc': excitation = self.excitation_hpc else: excitation = self.excitation if not self.dummy_debugging: time.sleep(0.3) try: sd.check_input_settings(channels=self.num_input_channels_used) sd.check_output_settings(channels=self.num_output_channels_used) except: print( "Audio hardware error! Too many channels or unsupported samplerate" ) return # do measurement recorded = sd.playrec(excitation, channels=self.num_input_channels_used) sd.wait() # get the recorded signals if self.channel_layout_input[0] >= 0: self.recorded_sweep_l = recorded[:, self.channel_layout_input[0]] else: self.recorded_sweep_l = np.zeros(np.size(recorded, 0)) if self.channel_layout_input[1] >= 0: self.recorded_sweep_r = recorded[:, self.channel_layout_input[1]] else: self.recorded_sweep_r = np.zeros(np.size(recorded, 0)) if self.feedback_loop_used: self.feedback_loop = recorded[:, self.channel_layout_input[2]] if abs(self.feedback_loop.max()) < 0.0001: self.feedback_loop = np.random.random_sample( self.feedback_loop.shape ) * 0.000001 # to avoid zero-division errors else: # if no FB loop, copy from original excitation sweep if type is 'hpc': self.feedback_loop = self.sweep_hpc_mono[:, 0] else: self.feedback_loop = self.sweep_mono[:, 0]
def play_record(frequency, tau = 90, fs = fsamp): #s, Hz, Hz myarray, Frec, tiempo = GeneradorArray(tau, [0, 1000, 0, 2000, 0, 3000, 0, 4000,0, 5000, 0, 6000, 0, 7000, 0, 8000, 0, 9000, 0, 10000, 0, 11000, 0, 12000, 0, 13000, 0, 14000, 0, 15000, 0, 16000, 0, 17000, 0, 18000, 0, 19000, 0, 20000, 0, 21000, 0, 22000, 0, 23000, 0, 24000, 0, 25000, 0]) t1 = time.time() myrecording = sd.playrec(myarray, samplerate=fs, channels=2) sd.wait() t2 = time.time() myrecording = np.transpose(myrecording) return tiempo, myrecording, t2-t1, myarray
def test(): test = append_waves(sine_wave(0, 0.5), sine_wave(1000, 0.5), make_header(), sine_wave(500, 1)) test /= 5 myrec = sd.playrec(test, 44100, 1) sd.wait() wave, noise = strip_wave(myrec, make_header()) head, noise = strip_wave(noise, make_header(), noise=True) return noise, head, wave # expect head.size = wave.size = noise.size = 44100
def play_record(audio): pause_length = 2.5 # seconds delay_length = 0.05 # seconds pause = np.zeros(int(pause_length * fs)) delay = np.zeros(int(delay_length * fs)) audio_with_pause = np.concatenate((pause, audio, delay)) recording, _ = sd.playrec(audio_with_pause), sd.wait() return recording[int((pause_length + delay_length) * fs):, 0]
def test_sd(): ## test des périphériques audio t = np.linspace(0,2,num=88200,endpoint=False) s1d=0*t s1g = AMP_REC*sgnl.tukey(88200,alpha=0.1)*np.cos(2*np.pi*440*t) myrecording = sd.playrec(np.array([s1g,s1d]).transpose(),44100,channels=2, blocking=True) plt.plot(myrecording) plt.show()
def playrec_onda(self, frec, amp=None, long=10): "pone una función onda y la graba al mismo tiempo. La salida de esta función es: un gráfico que muestra la señal que mandó y la que midió y el array correspondiente a la medición. " myrec = sd.playrec(self.crearOnda(frec, amp=amp, long=long), self.fs, channels=2) sd.wait() plt.plot(myrec) return myrec
def measure_audio_response(audio, fs, output_dir=None, name=None): print('Playing audio') output = sd.playrec(audio, fs) sd.wait() if output_dir and name: file = os.path.join(output_dir, name) sf.write(file, output, fs) print('Wrote audio to:', file) return output
def SoundCalIn(Rate, Freq, WaveDur, SBOutAmpF): """ Generate sine wave (1V to -1V) and read 1s of it. """ Pulse = GenSineWave(Rate, Freq, 0.05, WaveDur) SD.default.device = 'system' SD.default.samplerate = Rate SD.default.channels = 1 SD.default.blocksize = 0 SD.default.latency = 'low' print('Measuring... ', end='') Rec = SD.playrec(Pulse, blocking=True) print('Done.') return(Data)
time.sleep(1) print('4 ', end='') time.sleep(1) print('3 ', end='') time.sleep(1) print('2 ', end='') time.sleep(1) print('1 ') time.sleep(1) print('Sound measurement running...') time.sleep(1) for FKey in Sound: for AKey in Sound[FKey]: for Pulse in range(SoundPulseNo): SoundRec[FKey][AKey] = SD.playrec(Sound[FKey][AKey]); SD.wait() print('Done playing/recording. Saving data...') ## Save!!! os.makedirs(Folder, exist_ok=True) with h5py.File(FileName) as F: F.create_group('SoundRec') for FKey in SoundRec: F['SoundRec'].create_group(FKey) for AKey, AVal in SoundRec[FKey].items(): F['SoundRec'][FKey][AKey] = AVal for Key, Value in DataInfo.items(): F['SoundRec'].attrs[Key] = Value
from scripts import Transform, Window, DefaultFigures import numpy as np from scipy.signal import chirp import sounddevice as sd import matplotlib.pylab as plt # signal generation # allready exist N = 2 ** 16 fs = 2 ** 12 overlap = 50 # [%] t = np.arange(0, N / fs, 1 / fs) x = chirp(t, 20, N / fs - 1 / fs, 2000, phi=90) x = np.append(x, np.zeros(fs)) # silece for tail of real live sound y = sd.playrec(x, samplerate=fs, channels=1) sd.wait() y = np.reshape(y, len(y)) # averaging multiple signals # pass # for later on # window + multi fft Nw = fs hannw = Window.Window(Nw) (dummy, hann) = hannw.hanwind() S_1 = np.sum(hann) S_2 = np.sum(hann ** 2) NENBW = Nw * S_2 / (S_1 ** 2) ENBW = fs * S_2 / (S_1 ** 2) # = NENBW * fs/N
def PLAYREC(data, fs, channel): mysound = sd.playrec(data, fs, channels=2, blocking=True) # "blocking=True" is very important. return mysound