def generateSound(num, time, fs): n = time*fs x = np.linspace(0, time, n) if num == '0': freq1 = 1336 freq2 = 941 elif num == '1': freq1 = 1209 freq2 = 697 elif num == '2': freq1 = 1336 freq2 = 697 elif num == '3': freq1 = 1477 freq2 = 697 elif num == '4': freq1 = 1209 freq2 = 770 elif num == '5': freq1 = 1336 freq2 = 770 elif num == '6': freq1 = 1477 freq2 = 770 elif num == '7': freq1 = 1209 freq2 = 852 elif num == '8': freq1 = 1336 freq2 = 852 elif num == '9': freq1 = 1477 freq2 = 852 else: freq1 = 0 freq2 = 0 s1 = (np.sin(freq1*x*2*np.pi)) s2 = (np.sin(freq2*x*2*np.pi)) s = s1 + s2 sd.play(s, 44100) sd.wait() # Plotting graphs plt.figure(1) plt.subplot(211) plt.plot(s1) plt.xlim(0, 250) plt.subplot(211) plt.plot(s2) plt.xlim(0, 250) plt.subplot(212) plt.plot(s) plt.xlim(0, 250) plt.show() return
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 play(self, file_path): if self.convert: self.convert_mp3_to_wav(file_path_mp3=file_path) data, fs = sf.read(file_path) sd.play(data, fs) sd.wait()
def rec(fs, fn): sd.default.samplerate = fs sd.default.dtype = "int16" # fixme: uint? sd.default.channels = 1 duration = 10 X = sd.rec(duration * fs) X = (X.T)[0] sd.wait() write("e.wav", fs, X)
def run_test(time): duration = time # seconds fs = 48000 sd.default.samplerate = fs audio = sd.rec(duration * fs, channels=2, dtype="float64") sd.wait() combs = {} for pair in combinations(range(audio.shape[1]), 2): if not pair[0] in combs: combs[pair[0]] = {} shift = _compute_shift(audio[:, pair[1]], audio[:, pair[0]]) combs[pair[0]][pair[1]] = shift / (fs / 1000) return combs
def offline(): print("Offline analysis") duration = 5 # seconds fs = 48000 sd.default.samplerate = fs audio = sd.rec(duration * fs, channels=2, dtype="float64") sd.wait() print(" [{} channels, {:.2f} sec. {} Hz]".format(audio.shape[1], audio.shape[0] / fs, fs)) for pair in combinations(range(audio.shape[1]), 2): print(" Ch. {} -> {}:".format(*pair), end='') shift = _compute_shift(audio[:, pair[1]], audio[:, pair[0]]) print(" {:>5} sample(s) [{:>7,.3f} ms]".format(shift, shift / (fs / 1000))) sd.play(audio) sd.wait()
def audio_sample_generator(duration=10, sample_rate=2000): """ Yields a series of audio recordings from the system microphone. Args: duration (float): Time in seconds for each recording. sample_rate (float): Sample rate in Hz. Yields: numpy array: 1-d numpy array of audio data as int16 samples. """ samples = int(duration * sample_rate) while True: recording = sounddevice.rec(samples, samplerate=sample_rate, channels=1, dtype='int16') sounddevice.wait() yield recording[:, 0]
def record_sample(duration=3,samplerate=22050,channels=1,blocking=False): """ An optionally blocking method used to start the recording of a sample. Parameters: ----------- duration : int The length in seconds to record samplerate : int The number of samplesa per second to record at channels : int The number of channels to be used during recording blocking : bool True if method should block until it completes. False otherwise. """ sample=sd.rec(duration * samplerate, samplerate=samplerate, channels=channels, dtype='int16') if blocking == True: sd.wait() return sample
def reproducir(onda): play(to_wav(onda)) sd.wait()
import soundfile as sf # Use this package import sounddevice as sd # and this one kiss, samplerate = sf.read('Kiss.aiff') # load Kiss.aiff into kiss variable sd.play(kiss, samplerate*.8) # play the music at 80% speed sd.wait() # wait until music finishes before exiting
import random index = random.randint(0, len(x_val) - 1) samples = x_val[index].ravel() print("Audio:", classes[np.argmax(y_val[index])]) ipd.Audio(samples, rate=8000) print("Text:", predict(samples)) import sounddevice as sd import soundfile as sf samplerate = 16000 duration = 1 # seconds filename = 'yes.wav' print("start") mydata = sd.rec(int(samplerate * duration), samplerate=samplerate, channels=1, blocking=True) print("end") sd.wait() sf.write(filename, mydata, samplerate) os.listdir('../input/voice-commands/prateek_voice_v2') filepath = '../input/voice-commands/prateek_voice_v2' #reading the voice commands samples, sample_rate = librosa.load(filepath + '/' + 'stop.wav', sr=16000) samples = librosa.resample(samples, sample_rate, 8000) ipd.Audio(samples, rate=8000) predict(samples)
def play(self): import sounddevice as sd sd.default.channels = 2 sd.default.samplerate = self.sample_rate sd.play(self.play_data, self.sample_rate) sd.wait()
import sounddevice as sd from scipy.io.wavfile import write fs = 44100 # Sample rate seconds = 7 # Duration of recording myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2) sd.wait() # Wait until recording is finished write('output.wav', fs, myrecording) # Save as WAV file
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
def recordSound(): print("Recording for", duration ,"sec...") myrecording = sd.rec(int(duration * fs)) sd.wait() myrecording = myrecording[:,0] return myrecording
def Play_audio_filtrado(): sd.play(FilteredSignal * 50) sd.wait()
if FKey == str(len(FKeys)): break try: FKey = FKeys[int(FKey)] except IndexError: print('=== Wrong Freq index. Stopping... ===') print('') break AKeys = list(Sound[FKey].keys()); AKeys = sorted(AKeys, reverse=True) for AmpF, AKey in enumerate(AKeys): print('Playing', FKey, 'at', str(Intensities[AmpF]), 'dB') # Arduino.write(b'P') SD.play(Sound[FKey][AKey]); SD.wait() # Arduino.write(b'P') SD.play(SoundPauseBetweenStimBlocks); SD.wait() Hdf5F.WriteExpInfo('Sound', DVCoord, FKey, FileName) print('Played Freq', FKey, 'at', DVCoord, 'µm DV') #%% Run laser #DVCoord = input('Choose DVCoord (in µm): '); DVCoord = 'Out' # print('Running...') Arduino.write(b'P') for OneBlock in range(LaserStimBlockNo): for OnePulse in range(LaserPulseNo): # Arduino.write(b'b')
def Play_audio(): sd.play(y * 50) sd.wait()
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 19:55:13 2016 @author: SRINIVAS """ import sounddevice as sd import numpy as np print ("hello") fs= 44100 duration=4 recording = sd.rec(duration * fs, samplerate=fs, channels=2) sd.wait() fay=[] way=[] for p in range(1,fs*duration): fay.append(recording[p][0]) way.append(recording[p][0]) me=open('A.txt','a') for elem in fay: me.write(str(elem)) me.write('\n') me.close() em=open('B.txt','a') for elem in way:
def frequency_response(frequencies, amplitude=1, measuring_cycles=100, rancius_time=0.5, sampling_frequency=48000): # Validations ----------------------------------- if not isinstance(sampling_frequency, int): raise ValueError('sampling_frequency must be an integer number!') if amplitude > 1: raise ValueError( 'AMPLITUDE must be less than 1 because the output samples must lie between +-1' ) amplitudes = [None] * len(frequencies) phase = [None] * len(frequencies) for k in range(len(frequencies)): samples = np.sin( 2 * np.pi * np.arange(sampling_frequency / frequencies[k] * (rancius_time * frequencies[k] + measuring_cycles)) * frequencies[k] / sampling_frequency) samples -= np.min(samples) samples /= np.max(samples) samples -= 0.5 samples *= 2 * amplitude samples = samples.astype(np.float32) # Play and record samples ----------------------- recorded_samples = sd.playrec(samples, sampling_frequency, channels=2) sd.wait() #it waits and returns as the recording is finished. recorded_samples = np.transpose(recorded_samples) recorded_samples_fixed = [None] * 2 params = [None] * 2 for l in range(2): # Left and right channels. recorded_samples_fixed[l] = recorded_samples[l][ np.int(sampling_frequency * rancius_time):] # Discard rancius samples. # Fit sine to data: funcSin = lambda params, x: params[0] * np.sin(params[1] * x + params[2]) func = funcSin ErrorFunc = lambda params, x, y: func( params, x ) - y # ErrorFunc is the diference between the func and the y "experimental" data params0 = (1.0, frequencies[k] / sampling_frequency * 2 * np.pi, 0 ) # "First guess" of the parameters. params[l], success = opt.leastsq( ErrorFunc, params0[:], args=(np.arange(len(recorded_samples_fixed[l])), recorded_samples_fixed[l])) # f, axes = plt.subplots(2, sharex=True, figsize=(mplt.fig_width*mplt.fig_ratio[0]/25.4e-3, mplt.fig_width*mplt.fig_ratio[1]/25.4e-3)) # Create the figure for plotting. # f.subplots_adjust(hspace=0.3) # Fine-tune figure; make subplots close to each other and hide x ticks for all but bottom plot. # figs.append(f) # axes[0].plot(recorded_samples_fixed[0], color=mplt.colors[0], label='Data left') # axes[0].plot(func(params[0],np.arange(len(recorded_samples_fixed[0]))), color=mplt.colors[1], label='Fit left') # axes[1].plot(recorded_samples_fixed[1], color=mplt.colors[2], label='Data right') # axes[1].plot(func(params[1],np.arange(len(recorded_samples_fixed[1]))), color=mplt.colors[3], label='Fit right') amplitudes[k] = np.max(recorded_samples_fixed[0]) / np.max( recorded_samples_fixed[1]) phase[k] = (params[0][2] - params[1][2]) * 180 / np.pi # Phase difference. if phase[k] < -90: #so there are no phase breaks phase[k] = 180 + phase[k] if phase[k] < -90: phase[k] = 180 + phase[k] return np.array(amplitudes), np.array(phase)