def plot_response(): thinkplot.preplot(cols=2) response = thinkdsp.read_wave("180961__kleeb__gunshots.wav") response = response.segment(start=0.26, duration=5.0) response.normalize() response.plot() thinkplot.config(xlabel="time", xlim=[0, 5.0], ylabel="amplitude", ylim=[-1.05, 1.05]) thinkplot.subplot(2) transfer = response.make_spectrum() transfer.plot() thinkplot.config(xlabel="frequency", xlim=[0, 22500], ylabel="amplitude") thinkplot.save(root="systems6") wave = thinkdsp.read_wave("92002__jcveliz__violin-origional.wav") wave.ys = wave.ys[: len(response)] wave.normalize() spectrum = wave.make_spectrum() output = (spectrum * transfer).make_wave() output.normalize() wave.plot(color="0.7") output.plot(alpha=0.4) thinkplot.config(xlabel="time", xlim=[0, 5.0], ylabel="amplitude", ylim=[-1.05, 1.05]) thinkplot.save(root="systems7")
def violin_example(start=1.2, duration=0.6): """Demonstrates methods in the thinkdsp module. """ # read the violin recording wave = thinkdsp.read_wave('92002__jcveliz__violin-origional.wav') # extract a segment segment = wave.segment(start, duration) # make the spectrum spectrum = segment.make_spectrum() # apply a filter spectrum.low_pass(600) # invert the spectrum filtered = spectrum.make_wave() # prepare the original and filtered segments filtered.normalize() filtered.apodize() segment.apodize() # write the original and filtered segments to a file filename = 'filtered.wav' wfile = thinkdsp.WavFileWriter(filename, segment.framerate) wfile.write(segment) wfile.write(filtered) wfile.close() thinkdsp.play_wave(filename)
def segment_spectrum(filename, start, duration=1.0): """Plots the spectrum of a segment of a WAV file. Output file names are the given filename plus a suffix. filename: string start: start time in s duration: segment length in s """ wave = thinkdsp.read_wave(filename) plot_waveform(wave) # extract a segment segment = wave.segment(start, duration) segment.ys = segment.ys[:1024] print len(segment.ys) segment.normalize() segment.apodize() spectrum = segment.make_spectrum() segment.play() # plot the spectrum n = len(spectrum.hs) spectrum.plot() thinkplot.save(root=filename, xlabel='frequency (Hz)', ylabel='amplitude density')
def plot_bass(): wave = thinkdsp.read_wave('328878__tzurkan__guitar-phrase-tzu.wav') wave.normalize() wave.plot() wave.make_spectrum(full=True).plot() sampled = sample(wave, 4) sampled.make_spectrum(full=True).plot() spectrum = sampled.make_spectrum(full=True) boxcar = make_boxcar(spectrum, 4) boxcar.plot() filtered = (spectrum * boxcar).make_wave() filtered.scale(4) filtered.make_spectrum(full=True).plot() plot_segments(wave, filtered) diff = wave.ys - filtered.ys #thinkplot.plot(diff) np.mean(abs(diff)) sinc = boxcar.make_wave() ys = np.roll(sinc.ys, 50) thinkplot.plot(ys[:100])
def plot_beeps(): wave = thinkdsp.read_wave('253887__themusicalnomad__positive-beeps.wav') wave.normalize() thinkplot.preplot(3) # top left ax1 = plt.subplot2grid((4, 2), (0, 0), rowspan=2) plt.setp(ax1.get_xticklabels(), visible=False) wave.plot() thinkplot.config(title='Input waves', legend=False) # bottom left imp_sig = thinkdsp.Impulses([0.01, 0.4, 0.8, 1.2], amps=[1, 0.5, 0.25, 0.1]) impulses = imp_sig.make_wave(start=0, duration=1.3, framerate=wave.framerate) ax2 = plt.subplot2grid((4, 2), (2, 0), rowspan=2, sharex=ax1) impulses.plot() thinkplot.config(xlabel='Time (s)') # center right convolved = wave.convolve(impulses) ax3 = plt.subplot2grid((4, 2), (1, 1), rowspan=2) plt.title('Convolution') convolved.plot() thinkplot.config(xlabel='Time (s)') thinkplot.save(root='sampling1', formats=FORMATS, legend=False)
def segment_violin(start=1.2, duration=0.6): wave = thinkdsp.read_wave('92002__jcveliz__violin-origional.wav') # extract a segment segment = wave.segment(start, duration) segment.normalize() segment.apodize() segment.write('violin_segment1.wav') # plot the spectrum spectrum = segment.make_spectrum() n = len(spectrum.hs) spectrum.plot(high=n/2) thinkplot.Save(root='violin2', xlabel='frequency (Hz)', ylabel='amplitude density') # print the top 5 peaks peaks = spectrum.peaks() for amp, freq in peaks[:10]: print freq, amp # compare the segments to a 440 Hz Triangle wave note = thinkdsp.make_note(69, 0.6, sig_cons=thinkdsp.TriangleSignal, framerate=segment.framerate) wfile = thinkdsp.WavFileWriter('violin_segment2.wav', note.framerate) wfile.write(note) wfile.write(segment) wfile.write(note) wfile.close()
def plot_convolution(): response = thinkdsp.read_wave("180961__kleeb__gunshots.wav") response = response.segment(start=0.26, duration=5.0) response.normalize() dt = 1 shift = dt * response.framerate factor = 0.5 gun2 = response + shifted_scaled(response, shift, factor) gun2.plot() thinkplot.config(xlabel="time (s)", ylabel="amplitude", ylim=[-1.05, 1.05], legend=False) thinkplot.save(root="systems8") signal = thinkdsp.SawtoothSignal(freq=410) wave = signal.make_wave(duration=0.1, framerate=response.framerate) total = 0 for j, y in enumerate(wave.ys): total += shifted_scaled(response, j, y) total.normalize() wave.make_spectrum().plot(high=500, color="0.7", label="original") segment = total.segment(duration=0.2) segment.make_spectrum().plot(high=1000, label="convolved") thinkplot.config(xlabel="frequency (Hz)", ylabel="amplitude") thinkplot.save(root="systems9")
def segment_violin(start=1.2, duration=0.6): """Load a violin recording and plot its spectrum. start: start time of the segment in seconds duration: in seconds """ wave = thinkdsp.read_wave('92002__jcveliz__violin-origional.wav') # extract a segment segment = wave.segment(start, duration) segment.normalize() # plot the spectrum spectrum = segment.make_spectrum() thinkplot.preplot(1) spectrum.plot(high=10000) thinkplot.Save(root='sounds3', xlabel='Frequency (Hz)', ylabel='Amplitude', formats=FORMATS, legend=False) # print the top 5 peaks peaks = spectrum.peaks() for amp, freq in peaks[:10]: print(freq, amp)
def main(): # make_figures() wave = thinkdsp.read_wave('28042__bcjordan__voicedownbew.wav') wave.unbias() wave.normalize() track_pitch(wave) return thinkplot.preplot(rows=1, cols=2) plot_shifted(wave, 0.0003) thinkplot.config(xlabel='time (s)', ylabel='amplitude', ylim=[-1, 1]) thinkplot.subplot(2) plot_shifted(wave, 0.00225) thinkplot.config(xlabel='time (s)', ylim=[-1, 1]) thinkplot.save(root='autocorr3')
def __init__(self,filename = "flesh_wound.wav", signal_type = "saw", pitch = 240, num_channel = 1024, num_band = 32): self.num_bands = num_band self.num_channels = num_channel if filename == 'record': chunk = 1024 self.framerate = 41000 self.pya = pyaudio.PyAudio() # initialize pyaudio self.stream = self.pya.open(format = pyaudio.paInt16, channels = 1, rate = self.framerate, input = True, output = True, frames_per_buffer = chunk) data = get_samples_from_mic(self.framerate,300,chunk) self.voice_wave = thinkdsp.Wave(data,self.framerate) self.stream.close() self.pya.terminate() else: self.voice_wave = thinkdsp.read_wave(filename) # read in recording self.framerate= self.voice_wave.framerate # determine framerate self.duration = self.voice_wave.duration # determine duration self.voice_wave.normalize self.signal_type = signal_type # list of the type of signals to generate self.pitch = pitch # list of fundementals for the generated waves seg_voi = self.segmentor(self.voice_wave) self.sig_wave = self.Sig_generate() seg_sig = self.segmentor(self.sig_wave) voded_wave = self.vocode(seg_voi,seg_sig) self.vocoded_wave = voded_wave
def plot_amen2(): wave = thinkdsp.read_wave('263868__kevcio__amen-break-a-160-bpm.wav') wave.normalize() ax1 = thinkplot.preplot(6, rows=4) wave.make_spectrum(full=True).plot(label='spectrum') xlim = [-22050-250, 22050] thinkplot.config(xlim=xlim, xticklabels='invisible') ax2 = thinkplot.subplot(2) impulses = make_impulses(wave, 4) impulses.make_spectrum(full=True).plot(label='impulses') thinkplot.config(xlim=xlim, xticklabels='invisible') ax3 = thinkplot.subplot(3) sampled = wave * impulses spectrum = sampled.make_spectrum(full=True) spectrum.plot(label='sampled') thinkplot.config(xlim=xlim, xticklabels='invisible') ax4 = thinkplot.subplot(4) spectrum.low_pass(5512.5) spectrum.plot(label='filtered') thinkplot.config(xlim=xlim, xlabel='Frequency (Hz)') thinkplot.save(root='sampling4', formats=FORMATS)
def main(): wave = thinkdsp.read_wave('328878__tzurkan__guitar-phrase-tzu.wav') wave.normalize() plot_sampling3(wave, 'sampling5') plot_sincs(wave) plot_beeps() plot_am() wave = thinkdsp.read_wave('263868__kevcio__amen-break-a-160-bpm.wav') wave.normalize() plot_impulses(wave) plot_sampling(wave, 'sampling3') plot_sampling2(wave, 'sampling4')
def read_response(): """Reads the impulse response file and removes the initial silence. """ response = thinkdsp.read_wave('180960__kleeb__gunshot.wav') start = 0.26 response = response.segment(start=start) response.shift(-start) response.normalize() return response
def getSpectrum(start=0, duration=1, input_file="raw-epdf.wav", low_pass=22000, high_pass=20): # read the recording wave = thinkdsp.read_wave(input_file) segment = wave.segment(start, duration) spectrum = segment.make_spectrum() spectrum.low_pass(low_pass) spectrum.high_pass(high_pass) return spectrum
def violin_spectrogram(): """Makes a spectrogram of a violin recording. """ wave = thinkdsp.read_wave("92002__jcveliz__violin-origional.wav") seg_length = 2048 spectrogram = wave.make_spectrogram(seg_length) spectrogram.plot(high=seg_length / 8) # TODO: try imshow? thinkplot.save("spectrogram1", xlabel="time (s)", ylabel="frequency (Hz)", formats=["pdf"])
def vocode_audiofiles(filepath_1, filepath_2, num_filters=20, chunk_size=1024): """ "Fuses" two audiofiles using the Vocoder-algorithm. Note: If the length of the audiofiles differ, the longer file gets cut to the length of the shorter one. If the framerate differs, the file with the lower framerate is converted to the higher one, using the average-algorithm. # TODO: Implement what is described up there /\ :param filepath_1 (str): Path to a .wav file :param filepath_2 (str): Path to a .wav file :param num_filters (int: Amount of filters the vocoder uses :param chunk_size (int): Size each chunk should have (debug) :return: toolset.Wave """ assert isinstance(filepath_1, str) and isinstance(filepath_1, str), "Filepaths must be of type %s" % type(" ") wave1 = toolset.to_wave(thinkdsp.read_wave(filepath_1)) wave2 = toolset.to_wave(thinkdsp.read_wave(filepath_2)) smaller_signal_length = min(wave1.length, wave2.length) result = np.zeros(smaller_signal_length - (smaller_signal_length % chunk_size)) print "Starting to vocode two signals with length %i..." % smaller_signal_length vocoder = vc.Vocoder(wave1.framerate, np.hamming, num_filters, chunk_size) debug_num_chunks = len(result) / chunk_size - 1 debug_factor = 100.0 / debug_num_chunks for i in range(len(result) / chunk_size - 1): # Status update: print "%g%% done, processing chunk no. %i out of %i " % (round(i * debug_factor, 2), i, debug_num_chunks) # Start - und ende des momentanen Chunks berechnen: start, end = i * chunk_size, (i + 1) * chunk_size # Modulator- und Carrier-Chunk "herausschneiden": modulator = toolset.Wave(wave1.ys[start:end], wave1.framerate) carrier = toolset.Wave(wave2.ys[start:end], wave2.framerate) # Vocoder-Effekt auf die beiden Signale Anwenden: result[start:end] = vocoder.vocode(modulator, carrier) print "~job's done~" return toolset.Wave(result, wave1.framerate)
def plot_amen(): wave = thinkdsp.read_wave('263868__kevcio__amen-break-a-160-bpm.wav') wave.normalize() ax1 = thinkplot.preplot(2, rows=2) wave.make_spectrum(full=True).plot() xlim = [-22050, 22050] thinkplot.config(xlim=xlim, xticklabels='invisible') ax2 = thinkplot.subplot(2, sharey=ax1) sampled = sample(wave, 4) sampled.make_spectrum(full=True).plot() thinkplot.config(xlim=xlim, xlabel='Frequency (Hz)') thinkplot.show() return
def plot_correlate(): """Plots the autocorrelation function computed by np. """ wave = thinkdsp.read_wave('28042__bcjordan__voicedownbew.wav') wave.normalize() segment = wave.segment(start=0.2, duration=0.01) lags, corrs = autocorr(segment) N = len(segment) corrs2 = np.correlate(segment.ys, segment.ys, mode='same') lags = np.arange(-N//2, N//2) thinkplot.plot(lags, corrs2) thinkplot.config(xlabel='Lag', ylabel='Correlation', xlim=[-N//2, N//2]) thinkplot.save(root='autocorr9')
def plot_tuning(start=7.0, duration=0.006835): """Plots three cycles of a tuning fork playing A4. duration: float """ period = duration/3 freq = 1/period print period, freq wave = thinkdsp.read_wave('18871__zippi1__sound-bell-440hz.wav') segment = wave.segment(start, duration) segment.normalize() segment.plot() thinkplot.Save(root='tuning1', xlabel='time (s)', axis=[0, duration, -1.05, 1.05])
def plot_violin(start=1.30245, duration=0.00683): """Plots three cycles of a violin playing A4. duration: float """ period = duration/3 freq = 1/period print freq wave = thinkdsp.read_wave('92002__jcveliz__violin-origional.wav') segment = wave.segment(start, duration) segment.normalize() segment.plot() thinkplot.Save(root='violin1', xlabel='time (s)', axis=[0, duration, -1.05, 1.05])
def shade_silence(filename,start=0,end=None,disp=True,output=False, itr=''): """Find signal (as output) or silence (as shaded reagion in plot) in a audio file filename: (filepath) works best with .wav format start/end: (float or int) start/end time for duration of interest in second (default= entire length) disp: (bool) whether to display a plot(default= True) output: (bool) whether to return an output (default = False) itr: (int) iteration use for debugging purpose """ try: y, sr = librosa.load(filename) except: obj = thinkdsp.read_wave(filename) y = obj.ys sr = obj.framerate print itr, ' : librosa.load failed for '+filename t = np.arange(len(y))/sr i = int(round(start * sr)) if end != None: j = int(round(end * sr)) else: j = len(y) fills = findsilence(y[i:j],sr,i) if disp: fig, ax = plt.subplots() ax.set_title(filename) ax.plot(t[i:j],y[i:j]) if fills != None: shades = map(lambda x: (max(x[0],i),min(x[1],j)), fills) if len(shades)>0: shades = merger(shades) if disp: for s in shades: ax.axvspan(s[0]/sr, s[1]/sr, alpha=0.5, color='red') if len(shades)>1: live = map(lambda i: (shades[i][1],shades[i+1][0]),xrange(len(shades)-1)) elif len(shades)==1: a = [i,shades[0][0],shades[0][1],j] live = filter(lambda x: x != None, map(lambda x: tuple(x) if x[0]!=x[1] else None,np.sort(a).reshape((int(len(a)/2),2)))) else: live = [(i,j)] if output: return live, sr, len(y)
def getSignal(start=0, duration=1, input_file="raw-epdf.wav", low_pass=22000, high_pass=20): # read the recording wave = thinkdsp.read_wave(input_file) segment = wave.segment(start, duration) spectrum = segment.make_spectrum() spectrum.low_pass(low_pass) spectrum.high_pass(high_pass) # invert the spectrum filtered = spectrum.make_wave() # prepare the original and filtered segments filtered.normalize() filtered.apodize() # segment.apodize() return filtered
def plot_response(response): """Plots an input wave and the corresponding output. """ thinkplot.preplot(cols=2) response.plot() thinkplot.config(xlabel='Time (s)', xlim=[0.26, response.end], ylim=[-1.05, 1.05]) thinkplot.subplot(2) transfer = response.make_spectrum() transfer.plot() thinkplot.config(xlabel='Frequency (Hz)', xlim=[0, 22500], ylabel='Amplitude') thinkplot.save(root='systems6') violin = thinkdsp.read_wave('92002__jcveliz__violin-origional.wav') start = 0.11 violin = violin.segment(start=start) violin.shift(-start) violin.truncate(len(response)) violin.normalize() spectrum = violin.make_spectrum() output = (spectrum * transfer).make_wave() output.normalize() thinkplot.preplot(rows=2) violin.plot(label='input') thinkplot.config(xlim=[0, violin.end], ylim=[-1.05, 1.05]) thinkplot.subplot(2) output.plot(label='output') thinkplot.config(xlabel='Time (s)', xlim=[0, violin.end], ylim=[-1.05, 1.05]) thinkplot.save(root='systems7')
def __init__(self,filename = "flesh_wound.wav", signal_type = "saw", pitch = 440, num_channel = 1024, num_band = 32): self.num_bands = num_band self.num_channels = num_channel self.input = thinkdsp.read_wave(filename) self.input_spec = self.spectrum_gen(self.input) self.framerate = self.input.framerate self.duration = self.input.duration self.signal_type = signal_type self.pitch = pitch self.channel = self.Sig_generate() self.channel_spec = self.spectrum_gen(self.channel) input_seg = self.segmentor(self.input) channel_seg = self.segmentor(self.channel) voded_wave = self.vocode(input_seg,channel_seg) self.output = voded_wave self.output_spec = self.spectrum_gen(self.output)
def plot_violin(start=1.30245, duration=0.00683): """Plots three cycles of a violin playing A4. duration: float """ period = duration / 3 freq = 1 / period print(period, freq) assert abs(freq - 439.238653001) < 1e-7 wave = thinkdsp.read_wave("92002__jcveliz__violin-origional.wav") segment = wave.segment(start, duration) segment.normalize() thinkplot.preplot(1) segment.plot() thinkplot.Save( root="sounds2", xlabel="Time (s)", axis=[start, start + duration, -1.05, 1.05], formats=FORMATS, legend=False )
def plot_violin(start=1.30245, duration=0.00683): """Plots three cycles of a violin playing A4. duration: float """ period = duration/3 freq = 1/period print(period, freq) wave = thinkdsp.read_wave('92002__jcveliz__violin-origional.wav') segment = wave.segment(start, duration) segment.normalize() thinkplot.preplot(1) segment.plot() thinkplot.Save(root='sounds2', xlabel='Time (s)', axis=[start, start+duration, -1.05, 1.05], formats=FORMATS, legend=False)
def plot_tuning(start=7.0, duration=0.006835): """Plots three cycles of a bell playing A4. start: start time in seconds duration: float """ period = duration / 3 freq = 1 / period print(period, freq) assert abs(freq - 438.917337235) < 1e-7 wave = thinkdsp.read_wave("18871__zippi1__sound-bell-440hz.wav") segment = wave.segment(start, duration) segment.normalize() thinkplot.preplot(1) segment.plot() thinkplot.Save( root="sounds1", xlabel="Time (s)", axis=[start, start + duration, -1.05, 1.05], formats=FORMATS, legend=False )
def plot_am(): wave = thinkdsp.read_wave('105977__wcfl10__favorite-station.wav') wave.unbias() wave.normalize() # top ax1 = thinkplot.preplot(6, rows=4) spectrum = wave.make_spectrum(full=True) spectrum.plot(label='wave') xlim = [-22050, 22050] thinkplot.config(xlim=xlim, xticklabels='invisible') #second carrier_sig = thinkdsp.CosSignal(freq=10000) carrier_wave = carrier_sig.make_wave(duration=wave.duration, framerate=wave.framerate) modulated = wave * carrier_wave ax2 = thinkplot.subplot(2, sharey=ax1) modulated.make_spectrum(full=True).plot(label='modulated') thinkplot.config(xlim=xlim, xticklabels='invisible') # third demodulated = modulated * carrier_wave demodulated_spectrum = demodulated.make_spectrum(full=True) ax3 = thinkplot.subplot(3, sharey=ax1) demodulated_spectrum.plot(label='demodulated') thinkplot.config(xlim=xlim, xticklabels='invisible') #fourth ax4 = thinkplot.subplot(4, sharey=ax1) demodulated_spectrum.low_pass(10000) demodulated_spectrum.plot(label='filtered') thinkplot.config(xlim=xlim, xlabel='Frequency (Hz)') thinkplot.save(root='sampling2', formats=FORMATS)
def plot_correlate(): """Plots the autocorrelation function computed by numpy. """ wave = thinkdsp.read_wave('28042__bcjordan__voicedownbew.wav') wave.normalize() segment = wave.segment(start=0.2, duration=0.01) lags, corrs = autocorr(segment) corrs2 = numpy.correlate(segment.ys, segment.ys, mode='same') thinkplot.plot(corrs2) thinkplot.config(xlabel='lag', ylabel='correlation', xlim=[0, len(corrs2)]) thinkplot.save(root='autocorr9') N = len(corrs2) half = corrs2[N//2:] lengths = range(N, N//2, -1) half /= lengths half /= half[0]
def violinSignal(start=1.2, duration=0.6): """Demonstrates methods in the thinkdsp module. """ # read the violin recording wave = thinkdsp.read_wave('92002__jcveliz__violin-origional.wav') # extract a segment segment = wave.segment(start, duration) # make the spectrum spectrum = segment.make_spectrum() # apply a filter spectrum.low_pass(600) # invert the spectrum filtered = spectrum.make_wave() # prepare the original and filtered segments filtered.normalize() filtered.apodize() return filtered
def plot_singing_chirp(): """Makes a spectrogram of the vocal chirp recording. """ wave = thinkdsp.read_wave('28042__bcjordan__voicedownbew.wav') wave.normalize() duration = 0.01 segment = wave.segment(start=0.2, duration=duration) # plot two copies of the wave with a shift plot_shifted(wave, start=0.2, offset=0.0023) thinkplot.save(root='autocorr7') # plot the autocorrelation function lags, corrs = autocorr(segment) thinkplot.plot(lags, corrs) thinkplot.config(xlabel='Lag (index)', ylabel='Correlation', ylim=[-1.05, 1.05], xlim=[0, 225]) thinkplot.save(root='autocorr8') # plot the spectrogram gram = wave.make_spectrogram(seg_length=1024) gram.plot(high=4200) thinkplot.config(xlabel='Time (s)', ylabel='Frequency (Hz)', xlim=[0, 1.4], ylim=[0, 4200]) thinkplot.save(root='autocorr5') # plot the spectrum of one segment spectrum = segment.make_spectrum() spectrum.plot(high=1000) thinkplot.config(xlabel='Frequency (Hz)', ylabel='Amplitude') thinkplot.save(root='autocorr6')
def plot_am(): wave = thinkdsp.read_wave('105977__wcfl10__favorite-station.wav') wave.unbias() wave.normalize() # top ax1 = thinkplot.preplot(6, rows=4) spectrum = wave.make_spectrum(full=True) spectrum.plot(label='spectrum') thinkplot.config(xlim=XLIM, xticklabels='invisible') #second carrier_sig = thinkdsp.CosSignal(freq=10000) carrier_wave = carrier_sig.make_wave(duration=wave.duration, framerate=wave.framerate) modulated = wave * carrier_wave ax2 = thinkplot.subplot(2, sharey=ax1) modulated.make_spectrum(full=True).plot(label='modulated') thinkplot.config(xlim=XLIM, xticklabels='invisible') # third demodulated = modulated * carrier_wave demodulated_spectrum = demodulated.make_spectrum(full=True) ax3 = thinkplot.subplot(3, sharey=ax1) demodulated_spectrum.plot(label='demodulated') thinkplot.config(xlim=XLIM, xticklabels='invisible') #fourth ax4 = thinkplot.subplot(4, sharey=ax1) demodulated_spectrum.low_pass(10000) demodulated_spectrum.plot(label='filtered') thinkplot.config(xlim=XLIM, xlabel='Frequency (Hz)') thinkplot.save(root='sampling2', formats=FORMATS)
def segment_violin(start=1.2, duration=0.6): """Load a violin recording and plot its spectrum. start: start time of the segment in seconds duration: in seconds """ wave = thinkdsp.read_wave('92002__jcveliz__violin-origional.wav') # extract a segment segment = wave.segment(start, duration) segment.normalize() segment.apodize() segment.write('violin_segment1.wav') # plot the spectrum spectrum = segment.make_spectrum() n = len(spectrum.hs) spectrum.plot(high=n/2) thinkplot.Save(root='violin2', xlabel='frequency (Hz)', ylabel='amplitude density') # print the top 5 peaks peaks = spectrum.peaks() for amp, freq in peaks[:10]: print(freq, amp) # compare the segments to a 440 Hz Triangle wave note = thinkdsp.make_note(69, 0.6, sig_cons=thinkdsp.TriangleSignal, framerate=segment.framerate) wfile = thinkdsp.WavFileWriter('violin_segment2.wav', note.framerate) wfile.write(note) wfile.write(segment) wfile.write(note) wfile.close()
import sys sys.path.insert(0, 'ThinkDSP/code/') import thinkdsp import matplotlib.pyplot as pyplot # Read in audio file # FIXME - will this work for non wav files wave = thinkdsp.read_wave('test.wav') # Grab first 10 seconds of audio (you can ignore me) clipLength = 10 # in seconds index = 0 while (index < wave.ts.size and wave.ts[index] < clipLength): index += 1 # Remove extras wave.ts = wave.ts[:index] wave.ys = wave.ys[:index] # Play audio file wave.play() # Plot spectrum of audio file spectrum = wave.make_spectrum() spectrum.plot() pyplot.show()
import matplotlib.pyplot as plt # Genetic Programming from deap import algorithms from deap import base from deap import creator from deap import tools from deap import gp # Audio import librosa import librosa.display import thinkdsp # DADOS INICIAIS wave = thinkdsp.read_wave('sounds/92002__jcveliz__violin-origional.wav') target = wave.segment(1.18995, 0.62) # FUNCOES AUXILIARES PARA FITNESS def getMFCC(y, sr, is_print=False): ### MFC ### # Let's make and display a mel-scaled power (energy-squared) spectrogram S = librosa.feature.melspectrogram(y, sr=sr, n_mels=128) # Convert to log scale (dB). We'll use the peak power as reference. log_S = librosa.logamplitude(S, ref_power=np.max) if is_print: # Make a new figure plt.figure(figsize=(12, 4))
import os import matplotlib.pyplot as plt import thinkdsp as dsp from thinkdsp import read_wave from thinkdsp import decorate from IPython.display import display from thinkdsp import play_wave from ipywidgets import interact, fixed wave = read_wave( 'C:/Users/LENOVO/Desktop/xinhao/ThinkDSP/ThinkDSP/code/18871__zippi1__sound-bell-440hz.wav' ) wave.normalize() wave.make_audio() plt.subplot(231) wave.plot() segment = wave.segment(start=1.1, duration=0.5) segment.make_audio() plt.subplot(232) segment.plot() #plt.subplot(333) #segment.segment(start=1.1, duration=0.005).plot() spectrum = segment.make_spectrum() plt.subplot(233) spectrum.plot(high=7000) spectrum.low_pass(3500) plt.subplot(234) spectrum.plot(high=7000)
import sys sys.path.insert(1, 'dsp-modulo') from thinkdsp import Chirp from thinkdsp import read_wave import thinkplot #señal = Chirp(start=220, end=440, amp=1.0) #wave = señal.make_wave(duration=1, framerate=11025) wave = read_wave("telefono.wav") espectro = wave.make_spectrum() espectrograma = wave.make_spectrogram(seg_length=1024) wave.plot() thinkplot.show() espectro.plot() thinkplot.show() espectrograma.plot() thinkplot.show()
from __future__ import print_function, division import thinkdsp import thinkplot import numpy as np from ipywidgets import interact, interactive, fixed import ipywidgets as widgets from IPython.display import display wavesax = thinkdsp.read_wave("C:\som sax.wav") waveguitar = thinkdsp.read_wave('C:\som guitarra.wav') wavesax = thinkdsp.read_wave("..\Sons\som sax.wav") waveguitar = thinkdsp.read_wave('..\Sons\som guitarra.wav') spectrumSax = wavesax.make_spectrum() spectrumSax.plot(high=6000) spectrumGuitar = waveguitar.make_spectrum() spectrumGuitar.plot(high=1000) wavesax.normalize() wavesax.plot() segment = wavesax.segment(start=1.1, duration=1) segment.make_audio() segment.plot() segment.segment(start=1.1, duration=0.005).plot() spectrum = segment.make_spectrum() spectrum.plot(high=550) spectrum.low_pass(2000) spectrum.make_wave().make_audio()
get_ipython().system('wget https://github.com/DavronbekSattorov/ThinkDSP/blob/master/code/thinkdsp.py') # In[9]: if not os.path.exists('181934__landub__applause2.wav'): get_ipython().system('wget https://github.com/DavronbekSattorov/ThinkDSP/blob/master/code/181934__landub__applause2.wav') # In[10]: from thinkdsp import read_wave wave = read_wave('181934__landub__applause2.wav') wave.normalize() wave.make_audio() # In[11]: wave.plot() # In[12]: segment = wave.segment(start=1.1, duration=0.3) segment.make_audio()
from matplotlib import pyplot import thinkdsp wave = thinkdsp.read_wave(r"E:\folk.wav") pyplot.subplot(211) wave.plot() spectrum = wave.make_spectrum() pyplot.subplot(212) spectrum.plot() pyplot.show()
from thinkdsp import read_wave from thinkdsp import decorate from thinkdsp import play_wave wave = read_wave('download2.wav') start = 1.2 duration = 0.6 segment = wave.segment(start, duration) spectrum = wave.make_spectrum() # spectrum.low_pass(3000) #spectrum.high_pass(5000) spectrum.band_stop(3000, 5000) wave2 = spectrum.make_wave() wave2.play('temp.wav')
colName = "COLUMN{}".format(c) file.write(colName) file.write(',') file.write('\n') with open('../audio/birdsong/train/birdsong.json') as json_file: data = json.load(json_file) for b in data: try: #print(b) #print(b['file_id']) #print('******') fileName = filedir + 'xc' + str(b['file_id']) + '.wav' #print(fileName) test_wave = thinkdsp.read_wave(fileName) file.write(b['english_cname']) file.write(',') # print(test_wave.ys) # print(test_wave.ys.size) # print(test_wave.ts) spectrum = test_wave.make_spectrum() writeSpectogramToFile(file, spectrum) except FileNotFoundError: print('File not found error %s' % fileName) file.close() print('Finished')
from thinkdsp import decorate from thinkdsp import read_wave wave = read_wave('72475__rockwehrmann__glissup02.wav') wave.play() wave.make_spectrogram(512).plot(high=5000) decorate(xlabel='Time (s)', ylabel='Frequency (Hz)')
def abrirArchivo(): direccionArchivo = askopenfilename() strDireccionArchivo.set(direccionArchivo) telefono = "" waveTelefono = read_wave(direccionArchivo) segmentosNumero = [] for i in range(6): segmentosNumero.append( waveTelefono.segment(start=i * 0.5, duration=0.5)) #Atributos del espectro #hs: amplitud espectral #fs: frecuencias #hs[50000] fs[50000] #espectro = segmentosNumero[0].make_spectrum() #espectro.plot() #thinkplot.show() frecuenciasBajasDTMF = [697, 770, 852, 941] frecuenciasAltasDTMF = [1209, 1336, 1477] tolerancia = 10 for segmento in segmentosNumero: espectroSegmento = segmento.make_spectrum() frecuenciaDominantes = [] i = 0 for amplitudEspectral in espectroSegmento.hs: if numpy.abs(amplitudEspectral) > 500: frecuenciaDominantes.append(espectroSegmento.fs[i]) i = i + 1 frecuenciaBaja = 0 frecuenciaAlta = 0 for frecuencia in frecuenciaDominantes: for frecuenciaDTMF in frecuenciasBajasDTMF: if frecuencia > frecuenciaDTMF - tolerancia and frecuencia < frecuenciaDTMF + tolerancia: frecuenciaBaja = frecuenciaDTMF for frecuenciaDTMF in frecuenciasAltasDTMF: if frecuencia > frecuenciaDTMF - tolerancia and frecuencia < frecuenciaDTMF + tolerancia: frecuenciaAlta = frecuenciaDTMF if frecuenciaAlta == 1209: if frecuenciaBaja == 697: telefono = telefono + "1" elif frecuenciaBaja == 770: telefono = telefono + "4" elif frecuenciaBaja == 852: telefono = telefono + "7" elif frecuenciaBaja == 941: telefono = telefono + "*" else: telefono = telefono + "X" elif frecuenciaAlta == 1336: if frecuenciaBaja == 697: telefono = telefono + "2" elif frecuenciaBaja == 770: telefono = telefono + "5" elif frecuenciaBaja == 652: telefono = telefono + "8" elif frecuenciaBaja == 941: telefono = telefono + "0" else: telefono = telefono + "X" elif frecuenciaAlta == 1477: if frecuenciaBaja == 697: telefono = telefono + "3" elif frecuenciaBaja == 770: telefono = telefono + "6" elif frecuenciaBaja == 852: telefono = telefono + "9" elif frecuenciaBaja == 941: telefono = telefono + "#" else: telefono = telefono + "X" else: telefono = telefono + "X" strSecuencia.set(telefono) figure = Figure(figsize=(5, 3), dpi=100) figure.add_subplot(111).plot(waveTelefono.ts, waveTelefono.ys) canvas = FigureCanvasTkAgg(figure, master=principal) canvas.draw() canvas.get_tk_widget().pack()
thinkplot.plot(lags, corrs, label=label) np.random.seed(19) thinkplot.preplot(3) for beta in [1.7, 1.0, 0.3]: label = r'$\beta$ = %.1f' % beta plot_pink_autocorr(beta, label) thinkplot.config(xlabel='Lag', ylabel='Correlation', xlim=[-1, 1000], ylim=[-0.05, 1.05], legend=True) wave = thinkdsp.read_wave('28042__bcjordan__voicedownbew.wav') wave.normalize() wave.make_audio() spectrum = wave.make_spectrum() spectrum.plot() thinkplot.config(xlabel='Frequency (Hz)', ylabel='Amplitude') spectro = wave.make_spectrogram(seg_length=1024) spectro.plot(high=4200) thinkplot.config(xlabel='Time (s)', ylabel='Frequency (Hz)', xlim=[wave.start, wave.end]) duration = 0.01 segment = wave.segment(start=0.2, duration=duration)
import thinkdsp import thinkplot import thinkstats2 import numpy as np import scipy.fftpack import warnings warnings.filterwarnings('ignore') import dct %matplotlib qt5 # Saxaphone recording for sample wave = thinkdsp.read_wave('100475__iluppai__saxophone-weep.wav') wave.make_audio() # A short segment segment = wave.segment(start=1.2, duration=0.5) segment.normalize() segment.make_audio() # A DCT of that segment seg_dct = segment.make_dct() seg_dct.plot(high=4000) thinkplot.config(xlabel='Frequency (Hz)', ylabel='DCT') #This function takes a DCT and sets all elements below threshold to 0 def compress(dct, thresh=1): count = 0
from thinkdsp import read_wave from thinkdsp import Chirp from thinkdsp import normalize, unbias PI2 = np.pi * 2 class TromboneGliss(Chirp): def evaluate(self, ts): l1, l2 = 1.0 / self.start, 1.0 / self.end lengths = np.linspace(l1, l2, len(ts)) freqs = 1 / lengths dts = np.diff(ts, prepend=0) dphis = PI2 * freqs * dts phases = np.cumsum(dphis) ys = self.amp * np.cos(phases) return ys wave = read_wave('87778__marcgascon7__vocals.wav') wave.make_audio() wave.make_spectrogram(1024).plot(high=1000) # decorate(xlabel='Time (s)', ylabel='Frequency (Hz)') high = 1000 # segment = wave.segment(start=1, duration=0.25) # segment.make_spectrum().plot(high=high) segment = wave.segment(start=3.5, duration=0.25) segment.make_spectrum().plot(high=high) decorate(xlabel='Frequency (Hz)') plt.show()
from thinkdsp import read_wave import matplotlib.pyplot as plt from IPython.display import display wave = read_wave( 'd:/学习/数字信号处理/实验三/新建文件夹/263868__kevcio__amen-break-a-160-bpm.wav') wave.normalize() wave.make_audio() plt.subplot(4, 1, 1) wave.plot() segment = wave.segment(start=0.4, duration=0.1) plt.subplot(4, 1, 2) segment.plot() spectrum = segment.make_spectrum() plt.subplot(4, 1, 3) spectrum.plot(high=7000) spectrum.low_pass(5000) spectrum.high_pass(500) spectrum.band_stop(3000, 5000) plt.subplot(4, 1, 4) spectrum.make_wave().make_audio() spectrum.plot(high=7000) wave = spectrum.make_wave() wave.play('temp2.wav') plt.show()
from __future__ import print_function, division import thinkdsp import thinkplot import math import numpy %matplotlib inline zeroHighCutoff = 510 zeroLowCuttoff = 490 wave = thinkdsp.read_wave('receivedfile.wav') wave.normalize() wave.make_audio() windowSize = 0.5 results = []; for i in range(0, math.round(wave.duration / windowSize)): segment = wave.segment(i * windowSize, windowSize) segmentSpectrum = segment.make_spectrum() segmentSpectrum.low_pass(510) segmentSpectrum.high_pass(490) segmentSpectrum.apodize() if segementSpectrum[500] > .1: results[i] = 1
import sys sys.path.insert(1, 'dsp-modulo') from thinkdsp import read_wave from thinkdsp import decorate import thinkplot import numpy telefono = "" waveTelefono = read_wave("telefono(1).wav") segmentoNumero = [] for i in range(6): segmentoNumero.append(waveTelefono.segment(start=i * 0.5, duration=0.5)) #Atributos del espectro #hs: amplitud espectral #fs: frecuencias #hs[50000] fs[50000] #espectro = segmentoNumero[0].make_spectrum() #espectro.plot() #thinkplot.show() frecuenciasBajasDTMF = [697, 770, 852, 941] frecuenciasAltasDTMF = [1209, 1336, 1477] tolerancia = 10 for segmento in segmentoNumero: espectroSegmento = segmento.make_spectrum()
def plot_pink_autocorr(beta, label): signal = PinkNoise(beta=beta) wave = signal.make_wave(duration=1.0, framerate=10000) lags, corrs = autocorr(wave) plt.plot(lags, corrs, label=label) np.random.seed(19) for beta in [1.7, 1.0, 0.3]: label = r'$\beta$ = %.1f' % beta plot_pink_autocorr(beta, label) decorate(xlabel='Lag', ylabel='Correlation') plt.show() from thinkdsp import read_wave wave = read_wave('data/autocorrelation/28042__bcjordan__voicedownbew.wav') spectrum = wave.make_spectrum() spectrum.plot() decorate(xlabel='Frequency (Hz)', ylabel='Amplitude') plt.show() spectro = wave.make_spectrogram(seg_length=1024) spectro.plot(high=4200) decorate(xlabel='Time (s)', ylabel='Frequency (Hz)') plt.show()
from thinkdsp import read_wave import matplotlib.pyplot as plt from IPython.display import display wave = read_wave('trumpet.wav') #整个波形 wave.normalize() wave.make_audio() plt.subplot(4, 1, 1) wave.plot() #具有恒定音高的片段 #截取片段 segment = wave.segment(start=1.1, duration=0.3) segment.make_audio() plt.subplot(4, 1, 2) segment.plot() spectrum1 = segment.make_spectrum() wave1 = spectrum1.make_wave() wave1.play('temp1.wav') #频谱 spectrum = segment.make_spectrum() plt.subplot(4, 1, 3) spectrum.plot(high=7000) wave = read_wave('trumpet.wav') segment = wave.segment(1.1, 0.3) spectrum = segment.make_spectrum() spectrum.low_pass(5000) spectrum.high_pass(500) spectrum.band_stop(1600, 5000)
from thinkdsp import read_wave import matplotlib.pyplot as plt from IPython.display import display wave = read_wave('g:/学习/python1xxq/python/实验三/170255__dublie__trumpet.wav') #整个波形 wave.normalize() wave.make_audio() plt.subplot(4, 1, 1) wave.plot() #具有恒定音高的片段 #截取片段 segment = wave.segment(start=1.1, duration=0.3) segment.make_audio() plt.subplot(4, 1, 2) segment.plot() spectrum1 = segment.make_spectrum() wave1 = spectrum1.make_wave() wave1.play('temp1.wav') #频谱 spectrum = segment.make_spectrum() plt.subplot(4, 1, 3) spectrum.plot(high=7000) wave = read_wave('g:/学习/python1xxq/python/实验三/170255__dublie__trumpet.wav') segment = wave.segment(1.1, 0.3) spectrum = segment.make_spectrum() spectrum.low_pass(5000) spectrum.high_pass(500)
def Save_Show_Wave_Spec(x): WaveIn = read_wave('outputRecording'+str(x)+'.wav') dataW = WaveIn.ys dataW = np.asanyarray(dataW) sampling_rate = 46000 time = np.arange(len(dataW)) / sampling_rate #Array para eje x del ploteo (En Tiempo) fourier_transform = np.fft.fft(dataW) #Fourier Transform (Espectro normal) fourier_transform = np.asanyarray(np.abs(fourier_transform)) fs = np.fft.fftfreq(len(dataW),(1/sampling_rate)) #Array para eje x del ploteo (En Frecuencias) fs = np.asanyarray(np.abs(fs)) plt.plot(time, dataW,color='#3fb4c7') #Ploteo de onda original plt.xlabel('Tiempo (s)') plt.title('Onda #'+str(x)) plt.grid(True) plt.savefig('Wave'+str(x)+'.png') plt.clf() plt.plot(fs, fourier_transform,color='#3f76c7') #Ploteo de espectro de frecuencias plt.xlabel('Frecuencia (Hz)') plt.ylabel('Amplitud') plt.title('Espectro #'+str(x)) plt.grid(True) plt.savefig('Spectrum'+str(x)+'.png') plt.clf() PowSpec(fs,fourier_transform,x) #Espectro de poder #WaveImage wIn_Img=Image.open('Wave'+str(x)+'.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame4,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=x, column=5, sticky="nsew", padx=1, pady=1) #SpectrumImage sIn_Img=Image.open('Spectrum'+str(x)+'.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame4,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=x, column=6, sticky="nsew", padx=1, pady=1) #PowerSpectrumImage sIn_Img=Image.open('PowerSpectrum'+str(x)+'.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame4,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=x, column=7, sticky="nsew", padx=1, pady=1) ShowDuration(x) #Función para filtrado de señal #PASA-BAJO -> 10000 Hz #PASA-ALTO -> 1000 Hz #PASA-BANDA -> 1000-5000 Hz def low_pass(frecuencia_de_corte, factor=0)
def current_stats(): return None __main__(440, 'major') import thinkdsp import pyaudio import Record_audio as rec import wave import matplotlib.pyplot as plt import numpy as np import thinkplot f = thinkdsp.read_wave('menu_sleeping_demo_dj.wav') # spectrum = f.make_spectrum() # spectrum.plot() # the squiggly blue line # sp = spectrum.peaks() fig, ax = plt.subplots() # ok, i am currently not recording x=frequency, y=occurrences like ithought i was f.make_spectrum().plot(high=2000) thinkplot.config(title='working title', xlabel='frequency (Hz)', ylabel='number occurrences') thinkplot.show() f_spectrogram = f.make_spectrogram(seg_length=1024) f_spectrogram.plot(high=2000) thinkplot.config(title='working title',
def FiltrarS(S,F,Corte5): if (S==1): if (F==5): Recuperacion(S,Corte5) if (S==2): if (F==5): Recuperacion(S,Corte5) if (S==3): if (F==5): Recuperacion(S,Corte5) if (S==1) and (F==1): SFiltrar=read_wave('outputRecording'+str(S)+'.wav') EspFiltrar= SFiltrar.make_spectrum() EspFiltrar.low_pass(10000)#PASA-BAJO SFiltrada= EspFiltrar.make_wave() SFiltrada.normalize() SFiltrada.write('outputRecording_Filtered.wav') #Guardado y Mostrado de resultados SFiltrada.plot(color='#66a3ff') plt.xlabel('Tiempo (s)') plt.title('Onda Filtrada') plt.grid(True) plt.savefig('Filtered_Wave.png') plt.clf() EspFiltrar.plot(color='#ff471a') plt.xlabel('Frecuencia (Hz)') plt.title('Espectro Filtrado') plt.grid(True) plt.savefig('Filtered_Spectrum.png') plt.clf() #FilteredWaveImage wIn_Img=Image.open('Filtered_Wave.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame7,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=1, column=4, sticky="nsew", padx=1, pady=1) #FilteredSpectrumImage sIn_Img=Image.open('Filtered_Spectrum.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame7,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=1, column=5, sticky="nsew", padx=1, pady=1) if (S==1) and (F==2): SFiltrar=read_wave('outputRecording'+str(S)+'.wav') EspFiltrar= SFiltrar.make_spectrum() EspFiltrar.high_pass(1000)#PASA-ALTO SFiltrada= EspFiltrar.make_wave() SFiltrada.normalize() SFiltrada.write('outputRecording_Filtered.wav') #Guardado y Mostrado de resultados SFiltrada.plot(color='#66a3ff') plt.xlabel('Tiempo (s)') plt.title('Onda Filtrada') plt.grid(True) plt.savefig('Filtered_Wave.png') plt.clf() EspFiltrar.plot(color='#ff471a') plt.xlabel('Frecuencia (Hz)') plt.title('Espectro Filtrado') plt.grid(True) plt.savefig('Filtered_Spectrum.png') plt.clf() #FilteredWaveImage wIn_Img=Image.open('Filtered_Wave.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame7,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=1, column=4, sticky="nsew", padx=1, pady=1) #FilteredSpectrumImage sIn_Img=Image.open('Filtered_Spectrum.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame7,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=1, column=5, sticky="nsew", padx=1, pady=1) if (S==1) and (F==3): SFiltrar=read_wave('outputRecording'+str(S)+'.wav') EspFiltrar= SFiltrar.make_spectrum() EspFiltrar.band_stop(1000,5000)#PASA-BANDA SFiltrada= EspFiltrar.make_wave() SFiltrada.normalize() SFiltrada.write('outputRecording_Filtered.wav') #Guardado y Mostrado de resultados SFiltrada.plot(color='#66a3ff') plt.xlabel('Tiempo (s)') plt.title('Onda Filtrada') plt.grid(True) plt.savefig('Filtered_Wave.png') plt.clf() EspFiltrar.plot(color='#ff471a') plt.xlabel('Frecuencia (Hz)') plt.title('Espectro Filtrado') plt.grid(True) plt.savefig('Filtered_Spectrum.png') plt.clf() #FilteredWaveImage wIn_Img=Image.open('Filtered_Wave.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame7,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=1, column=4, sticky="nsew", padx=1, pady=1) #FilteredSpectrumImage sIn_Img=Image.open('Filtered_Spectrum.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame7,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=1, column=5, sticky="nsew", padx=1, pady=1) if (S==2) and (F==1): SFiltrar=read_wave('outputRecording'+str(S)+'.wav') EspFiltrar= SFiltrar.make_spectrum() EspFiltrar.low_pass(10000)#PASA-BAJO SFiltrada= EspFiltrar.make_wave() SFiltrada.normalize() SFiltrada.write('outputRecording_Filtered.wav') #Guardado y Mostrado de resultados SFiltrada.plot(color='#66a3ff') plt.xlabel('Tiempo (s)') plt.title('Onda Filtrada') plt.grid(True) plt.savefig('Filtered_Wave.png') plt.clf() EspFiltrar.plot(color='#ff471a') plt.xlabel('Frecuencia (Hz)') plt.title('Espectro Filtrado') plt.grid(True) plt.savefig('Filtered_Spectrum.png') plt.clf() #FilteredWaveImage wIn_Img=Image.open('Filtered_Wave.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame7,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=1, column=4, sticky="nsew", padx=1, pady=1) #FilteredSpectrumImage sIn_Img=Image.open('Filtered_Spectrum.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame7,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=1, column=5, sticky="nsew", padx=1, pady=1) if (S==2) and (F==2): SFiltrar=read_wave('outputRecording'+str(S)+'.wav') EspFiltrar= SFiltrar.make_spectrum() EspFiltrar.high_pass(1000)#PASA-ALTO SFiltrada= EspFiltrar.make_wave() SFiltrada.normalize() SFiltrada.write('outputRecording_Filtered.wav') #Guardado y Mostrado de resultados SFiltrada.plot(color='#66a3ff') plt.xlabel('Tiempo (s)') plt.title('Onda Filtrada') plt.grid(True) plt.savefig('Filtered_Wave.png') plt.clf() EspFiltrar.plot(color='#ff471a') plt.xlabel('Frecuencia (Hz)') plt.title('Espectro Filtrado') plt.grid(True) plt.savefig('Filtered_Spectrum.png') plt.clf() #FilteredWaveImage wIn_Img=Image.open('Filtered_Wave.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame7,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=1, column=4, sticky="nsew", padx=1, pady=1) #FilteredSpectrumImage sIn_Img=Image.open('Filtered_Spectrum.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame7,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=1, column=5, sticky="nsew", padx=1, pady=1) if (S==2) and (F==3): SFiltrar=read_wave('outputRecording'+str(S)+'.wav') EspFiltrar= SFiltrar.make_spectrum() EspFiltrar.band_stop(1000,5000)#PASA-BANDA SFiltrada= EspFiltrar.make_wave() SFiltrada.normalize() SFiltrada.write('outputRecording_Filtered.wav') #Guardado y Mostrado de resultados SFiltrada.plot(color='#66a3ff') plt.xlabel('Tiempo (s)') plt.title('Onda Filtrada') plt.grid(True) plt.savefig('Filtered_Wave.png') plt.clf() EspFiltrar.plot(color='#ff471a') plt.xlabel('Frecuencia (Hz)') plt.title('Espectro Filtrado') plt.grid(True) plt.savefig('Filtered_Spectrum.png') plt.clf() #FilteredWaveImage wIn_Img=Image.open('Filtered_Wave.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame7,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=1, column=4, sticky="nsew", padx=1, pady=1) #FilteredSpectrumImage sIn_Img=Image.open('Filtered_Spectrum.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame7,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=1, column=5, sticky="nsew", padx=1, pady=1) if (S==3) and (F==1): SFiltrar=read_wave('outputRecording'+str(S)+'.wav') EspFiltrar= SFiltrar.make_spectrum() EspFiltrar.low_pass(10000)#PASA-BAJO SFiltrada= EspFiltrar.make_wave() SFiltrada.normalize() SFiltrada.write('outputRecording_Filtered.wav') #Guardado y Mostrado de resultados SFiltrada.plot(color='#66a3ff') plt.xlabel('Tiempo (s)') plt.title('Onda Filtrada') plt.grid(True) plt.savefig('Filtered_Wave.png') plt.clf() EspFiltrar.plot(color='#ff471a') plt.xlabel('Frecuencia (Hz)') plt.title('Espectro Filtrado') plt.grid(True) plt.savefig('Filtered_Spectrum.png') plt.clf() #FilteredWaveImage wIn_Img=Image.open('Filtered_Wave.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame7,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=1, column=4, sticky="nsew", padx=1, pady=1) #FilteredSpectrumImage sIn_Img=Image.open('Filtered_Spectrum.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame7,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=1, column=5, sticky="nsew", padx=1, pady=1) if (S==3) and (F==2): SFiltrar=read_wave('outputRecording'+str(S)+'.wav') EspFiltrar= SFiltrar.make_spectrum() EspFiltrar.high_pass(1000)#PASA-ALTO SFiltrada= EspFiltrar.make_wave() SFiltrada.normalize() SFiltrada.write('outputRecording_Filtered.wav') #Guardado y Mostrado de resultados SFiltrada.plot(color='#66a3ff') plt.xlabel('Tiempo (s)') plt.title('Onda Filtrada') plt.grid(True) plt.savefig('Filtered_Wave.png') plt.clf() EspFiltrar.plot(color='#ff471a') plt.xlabel('Frecuencia (Hz)') plt.title('Espectro Filtrado') plt.grid(True) plt.savefig('Filtered_Spectrum.png') plt.clf() #FilteredWaveImage wIn_Img=Image.open('Filtered_Wave.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame7,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=1, column=4, sticky="nsew", padx=1, pady=1) #FilteredSpectrumImage sIn_Img=Image.open('Filtered_Spectrum.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame7,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=1, column=5, sticky="nsew", padx=1, pady=1) if (S==3) and (F==3): SFiltrar=read_wave('outputRecording'+str(S)+'.wav') EspFiltrar= SFiltrar.make_spectrum() EspFiltrar.band_stop(1000,5000)#PASA-BANDA SFiltrada= EspFiltrar.make_wave() SFiltrada.normalize() SFiltrada.write('outputRecording_Filtered.wav') #Guardado y Mostrado de resultados SFiltrada.plot(color='#66a3ff') plt.xlabel('Tiempo (s)') plt.title('Onda Filtrada') plt.grid(True) plt.savefig('Filtered_Wave.png') plt.clf() EspFiltrar.plot(color='#ff471a') plt.xlabel('Frecuencia (Hz)') plt.title('Espectro Filtrado') plt.grid(True) plt.savefig('Filtered_Spectrum.png') plt.clf() #FilteredWaveImage wIn_Img=Image.open('Filtered_Wave.png') wIn_Img = wIn_Img.resize((int((wIn_Img.width)-((wIn_Img.width)*0.5)),int((wIn_Img.height)-((wIn_Img.height)*0.5))), Image.ANTIALIAS) render1=ImageTk.PhotoImage(wIn_Img) wIn_Label = Label(frame7,image=render1) wIn_Label.image = render1 wIn_Label.grid(row=1, column=4, sticky="nsew", padx=1, pady=1) #FilteredSpectrumImage sIn_Img=Image.open('Filtered_Spectrum.png') sIn_Img = sIn_Img.resize((int((sIn_Img.width)-((sIn_Img.width)*0.5)),int((sIn_Img.height)-((sIn_Img.height)*0.5))), Image.ANTIALIAS) render2=ImageTk.PhotoImage(sIn_Img) sIn_Label = Label(frame7,image=render2) sIn_Label.image=render2 sIn_Label.grid(row=1, column=5, sticky="nsew", padx=1, pady=1)
# -*- coding: utf-8 -*- """ Created on Wed May 26 08:36:57 2021 @author: GML """ from thinkdsp import read_wave wave = read_wave('aaa.wav') wave.normalize() wave.make_audio() wave.plot()
def abrirArchivo(): direccionArchivo = askopenfilename() strDireccionArchivo.set("Direccion del archivo: " + direccionArchivo) tamanoSegmento = 0 tamanoLetras = 0 palabra = "" wavePalabra = read_wave(direccionArchivo) primerSegmentoLetras = [] primerSegmentoLetras.append(wavePalabra.segment(start=0, duration=0.5)) frecuenciasSegmentos = [300, 400, 500, 600] frecuenciasNumeroLetras = [2000, 2600, 2300, 3200, 3500, 2900, 3800] tolerancia = 10 for segmento in primerSegmentoLetras: espectroSegmento = segmento.make_spectrum() frecuenciasDominantes = [] i = 0 for amplitudEspectral in espectroSegmento.hs: if numpy.abs(amplitudEspectral) > 500: frecuenciasDominantes.append(espectroSegmento.fs[i]) i = i + 1 sizeSegmento = 0 cantidadLetras = 0 for frecuencia in frecuenciasDominantes: for frecuenciaDTMF in frecuenciasSegmentos: if frecuencia > frecuenciaDTMF - tolerancia and frecuencia < frecuenciaDTMF + tolerancia: sizeSegmento = frecuenciaDTMF for frecuenciaDTMF in frecuenciasNumeroLetras: if frecuencia > frecuenciaDTMF - tolerancia and frecuencia < frecuenciaDTMF + tolerancia: cantidadLetras = frecuenciaDTMF if sizeSegmento == 300: tamanoSegmento = 0.3 elif sizeSegmento == 400: tamanoSegmento = 0.4 elif sizeSegmento == 500: tamanoSegmento = 0.5 elif sizeSegmento == 600: tamanoSegmento = 0.6 if cantidadLetras == 2000: tamanoLetras = 2 elif cantidadLetras == 2600: tamanoLetras = 3 elif cantidadLetras == 2300: tamanoLetras = 4 elif cantidadLetras == 3200: tamanoLetras = 5 elif cantidadLetras == 3500: tamanoLetras = 6 elif cantidadLetras == 2900: tamanoLetras = 7 elif cantidadLetras == 3800: tamanoLetras = 8 segmentoLetras = [] for i in range(tamanoLetras): segmentoLetras.append( wavePalabra.segment(start=0.5 + i * tamanoSegmento, duration=tamanoSegmento)) frecuenciaLetras = [ 2000, 5600, 9200, 2400, 6000, 9600, 2800, 6400, 10000, 3200, 6800, 10400, 3600, 7200, 10800, 4000, 7600, 11200, 4400, 8000, 11600, 4800, 8400, 12000, 5200, 8800 ] for segmento in segmentoLetras: espectroSegmento = segmento.make_spectrum() frecuenciasDominantes = [] i = 0 for amplitudEspectral in espectroSegmento.hs: if numpy.abs(amplitudEspectral) > 500: frecuenciasDominantes.append(espectroSegmento.fs[i]) i = i + 1 letras = 0 for frecuencia in frecuenciasDominantes: for frecuenciaDTMF in frecuenciaLetras: if frecuencia > frecuenciaDTMF - tolerancia and frecuencia < frecuenciaDTMF + tolerancia: letras = frecuenciaDTMF if letras == 2000: palabra = palabra + "A" elif letras == 5600: palabra = palabra + "B" elif letras == 9200: palabra = palabra + "C" elif letras == 2400: palabra = palabra + "D" elif letras == 6000: palabra = palabra + "E" elif letras == 9600: palabra = palabra + "F" elif letras == 2800: palabra = palabra + "G" elif letras == 6400: palabra = palabra + "H" elif letras == 10000: palabra = palabra + "I" elif letras == 3200: palabra = palabra + "J" elif letras == 6800: palabra = palabra + "K" elif letras == 10400: palabra = palabra + "L" elif letras == 3600: palabra = palabra + "M" elif letras == 7200: palabra = palabra + "N" elif letras == 10800: palabra = palabra + "O" elif letras == 4000: palabra = palabra + "P" elif letras == 7600: palabra = palabra + "Q" elif letras == 11200: palabra = palabra + "R" elif letras == 4400: palabra = palabra + "S" elif letras == 8000: palabra = palabra + "T" elif letras == 11600: palabra = palabra + "U" elif letras == 4800: palabra = palabra + "V" elif letras == 8400: palabra = palabra + "W" elif letras == 12000: palabra = palabra + "X" elif letras == 5200: palabra = palabra + "Y" elif letras == 8800: palabra = palabra + "W" strSecuencia.set("Numero de contenido en el audio: " + palabra) figure = Figure(figsize=(5, 3), dpi=100) figure.add_subplot(111).plot(wavePalabra.ts, wavePalabra.ys) canvas = FigureCanvasTkAgg(figure, master=principal) canvas.draw() canvas.get_tk_widget().pack()
import sys sys.path.insert(1, 'dsp-modulo') from thinkdsp import read_wave from thinkdsp import decorate import thinkplot import numpy telefono = "" waveTelefono = read_wave("telefono.wav") #arreglo para guardar cada uno de los segmentos segmentosNumeros = [] #rango es del 0-5 for i in range(6): segmentosNumeros.append(waveTelefono.segment(start=i * 0.5, duration=0.5)) #Atributos del espectro #hs:amplitud espectral #fs:frecuencias #espectro = segmentosNumeros[0].make_spectrum() #espectro.plot() #thinkplot.show() frecuenciasBajasDTMF = [697, 770, 852, 941] frecuenciasAltasDTMF = [1209, 1336, 1477] tolerancia = 10
from thinkdsp import CosSignal, SinSignal, decorate, read_wave import matplotlib.pyplot as plt wave = read_wave(r'C:\Users\Mia\Desktop\study\code_170255_dublie_trumpet.wav') #wave.normalize() #wave.make_audio() #plt.subplot(121) #wave.plot() #segment = wave.segment(start=1.1, duration=0.3) #segment.make_audio() #plt.subplot(122) #segment.plot() #segment.segment(start=1.1, duration=0.005).plot() #spectrum = segment.make_spectrum() #plt.subplot(121) #spectrum.plot(high=7000) #spectrum.low_pass(4000) #plt.subplot(122) #spectrum.plot(high=7000) #spectrum.high_pass(1000) #plt.subplot(121) #spectrum.plot(high=7000) #spectrum.band_stop(2500,1000) #plt.subplot(122) #spectrum.plot(high=7000) #plt.show() ''' cos_sig = CosSignal(freq=440,amp=1.0,offset=0) sin_sig = SinSignal(freq=880,amp=2.0,offset=0) plt.subplot(231) cos_sig.plot()