SHARE
TWEET

Untitled

a guest Apr 22nd, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from scipy import signal
  4. import scipy.io.wavfile as wavf
  5. import pandas as pd
  6.  
  7. from scipy.io import wavfile
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10.  
  11. class ChordWav:
  12.     def __init__(self):
  13.         """Does nothing"""
  14.  
  15.     def input_data(self, fs, data, mono=False):
  16.         self._fs = fs
  17.         wav_arr = data
  18.         if mono:
  19.             wav_arr_mono = wav_arr
  20.         else:
  21.             wav_arr_mono = []
  22.             wav_arr = wav_arr.T
  23.             for i in range(0, len(wav_arr[0])):
  24.                 wav_arr_mono.append((wav_arr[0][i] + wav_arr[1][i]) / 2)
  25.  
  26.         self._samples = len(wav_arr_mono)
  27.         self._times = np.linspace(0, len(wav_arr_mono) / self._fs,
  28.                 len(wav_arr_mono))
  29.         self._amplitudes = np.array(wav_arr_mono)
  30.  
  31.     def load_file(self, f, mono=False):
  32.         self._fs, wav_arr = wavfile.read(f)
  33.         if mono:
  34.             wav_arr_mono = wav_arr
  35.         else:
  36.             wav_arr_mono = []
  37.             wav_arr = wav_arr.T
  38.             for i in range(0, len(wav_arr[0])):
  39.                 wav_arr_mono.append((wav_arr[0][i] + wav_arr[1][i]) / 2)
  40.         self._samples = len(wav_arr_mono)
  41.         self._times = np.linspace(0, len(wav_arr_mono) / self._fs,
  42.                 len(wav_arr_mono))
  43.         self._amplitudes = np.array(wav_arr_mono)
  44.  
  45.     def data(self):
  46.         return (self._times, self._amplitudes)
  47.  
  48.     _dft = np.array([])
  49.     def dft(self, force=False):
  50.         if force or self._dft.size == 0:
  51.             self._dft = np.fft.fft(self._amplitudes) / self._samples
  52.             self._dft = self._dft[range(int(self._samples / 2))]
  53.         return self._dft
  54.  
  55.     _abs_dft_freq = np.array([])
  56.     _abs_dft = np.array([])
  57.     def abs_dft(self, force=False):
  58.         if force or not self._abs_dft.size or not self._abs_dft_freq.size:
  59.             frq = np.arange(self._samples) * self._fs / self._samples
  60.             self._abs_dft_freq = frq[range(int(self._samples / 2))]
  61.             self._abs_dft = abs(self.dft())
  62.         return self._abs_dft_freq, self._abs_dft
  63.  
  64.     def fft_peaks(self, cutoff=0.30, leway=15):
  65.         """Returns an array at which the frequencies are above the mode of the
  66.         array returned by self.abs_dft()"""
  67.         x, y = self.abs_dft()
  68.         y = y / np.amax(y) # Normalizes so that the maximum value is 1
  69.         peaks = []
  70.         for i, val in enumerate(y):
  71.             if val > cutoff:
  72.                 peaks.append(x[i])
  73.  
  74.         plt.plot(x, y)
  75.         plt.plot(x, np.full(y.size, cutoff))
  76.  
  77.         peaks_final = []
  78.         y_final = []
  79.         for peak_a in peaks:
  80.             if not any(np.abs(peak_a - peak_b) < leway
  81.                     for peak_b in peaks_final):
  82.                 peaks_final.append(peak_a)
  83.             else:
  84.                 closest_value_index = (np.abs(peaks_final - peak_a)).argmin()
  85.                 peaks_final[closest_value_index] = \
  86.                         (peaks_final[closest_value_index] + peak_a) / 2
  87.  
  88.         return peaks_final, y_final
  89.  
  90.     def plot(self):
  91.         plt.plot(self._times, self._amplitudes, linewidth=0.1)
  92.  
  93.     def plot_ft(self):
  94.         x, y = self.abs_dft()
  95.         plt.plot(x, y, linewidth=0.2)
  96.  
  97.  
  98. def sine_generator(fs, sinefreq, duration):
  99.     T = duration
  100.     nsamples = fs * T
  101.     w = 2. * np.pi * sinefreq
  102.     t_sine = np.linspace(0, T, nsamples, endpoint=False)
  103.     y_sine = np.sin(w * t_sine)
  104.     result = pd.DataFrame({
  105.         'data' : y_sine
  106.         }, index=t_sine)
  107.     return result
  108.  
  109. def butter_highpass(cutoff, fs, order=5):
  110.     nyq = 0.5 * fs
  111.     normal_cutoff = cutoff / nyq
  112.     b, a = signal.butter(order, normal_cutoff, btype='high', analog=False)
  113.     return b, a
  114.  
  115. def butter_highpass_filter(data, cutoff, fs, order=5):
  116.     b, a = butter_highpass(cutoff, fs, order=order)
  117.     y = signal.filtfilt(b, a, data)
  118.     return y
  119.  
  120. cw = ChordWav()
  121. cw.load_file("f.wav", mono=True)
  122. time, input_data = cw.data()
  123.  
  124. fs = 44100
  125.  
  126. filtered_data = butter_highpass_filter(input_data, 200, fs)
  127.  
  128. plt.plot(time, input_data, linewidth=0.2)
  129. plt.xlabel('Time [s]')
  130. plt.ylabel('Relative Amplitude')
  131. plt.title('Input Waveform')
  132. plt.show()
  133.  
  134. cw.plot_ft()
  135. plt.xlabel('Frequency [Hz]')
  136. plt.ylabel('Relative Amplitude')
  137. plt.title('Frequency Graph of the Input Waveform')
  138. plt.show()
  139.  
  140. plt.plot(time, filtered_data, linewidth=0.2)
  141. plt.xlabel('Time [s]')
  142. plt.ylabel('Relative Amplitude')
  143. plt.title('Filtered Waveform')
  144. plt.show()
  145.  
  146. cwf = ChordWav()
  147. cwf.input_data(fs, filtered_data, mono=True)
  148. cwf.plot_ft()
  149. plt.xlabel('Frequency [Hz]')
  150. plt.ylabel('Relative Amplitude')
  151. plt.title('Frequency Graph of the Filtered Waveform')
  152. plt.show()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top