#!/bin/python # -*- coding: utf-8 -*- # vim: set fileencoding= : """ This function to explain Laurel & Yanny hearing illusion """ __version_info__ = ('12', '04', '2020') __version__ = '_'.join(__version_info__) __author__ = 'Hitham Jleed' print (__doc__) print ('version: ',__version__) print ('author: ',__author__) import numpy as np # matplotlib for displaying the output import matplotlib.pyplot as plt import matplotlib.style as ms ms.use('seaborn-muted') # Librosa for audio import librosa # And the display module for visualization import librosa.display # Read the audio file. sr is the default sampling rate of 22050 y, sr = librosa.load('audio.wav') def plot_time(x,sr,mytitle,savedname): Time = np.linspace(0, len(x) / sr, num=len(x)) # define time in seconds plt.figure(figsize=(12,4)) plt.plot(Time, x) plt.title(mytitle) plt.grid(True) plt.tight_layout() plt.savefig(savedname, bbox_inches='tight') plt.show() def display_mel_spectogram(y, sr,mytitle,savedname): S = librosa.feature.melspectrogram(y, sr=sr, n_mels=128) # Convert to log scale (dB) log_S = librosa.power_to_db(S, ref=np.max) # Make a new figure plt.figure(figsize=(12,4)) # Display the spectrogram on a mel scale # sample rate and hop length parameters are used to render the time axis librosa.display.specshow(log_S, sr=sr, x_axis='time', y_axis='mel') # draw a color bar plt.colorbar(format='%+02.0f dB') # Make the figure layout compact plt.title(mytitle) plt.grid(True) plt.tight_layout() plt.savefig(savedname, bbox_inches='tight') plt.show() # display the original signal plot_time(y,sr,'original','orig_time.png') display_mel_spectogram(y, sr,'original','orig_spec.png') # Define a function which wil apply a butterworth bandpass filter from scipy.signal import butter, lfilter def butter_bandpass(lowcut, highcut, fs, order=5): nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') return b, a def butter_bandpass_filter(data, lowcut, highcut, fs, order=5): b, a = butter_bandpass(lowcut, highcut, fs, order=order) y = lfilter(b, a, data) return y # Now use butter_bandpass_filter to split the signal about the 1024 hz mark signal_upper = butter_bandpass_filter(y, 2548, 6500, sr) librosa.output.write_wav('Yanny.wav', signal_upper, sr) # display Yanny signal plot_time(signal_upper,sr,'Yanny','Yanny_time.png') display_mel_spectogram(signal_upper, sr,'Yanny','Yanny_spec.png') # the lower part signal_lower = butter_bandpass_filter(y, 50, 1024, sr) librosa.output.write_wav('Laurel.wav', signal_lower, sr) # display Yanny signal plot_time(signal_lower,sr,'Laurel','Laurel_time.png') display_mel_spectogram(signal_lower, sr,'Laurel','Laurel_spec.png')