paster442

Amplitude of Audio File in Python

Aug 21st, 2021 (edited)
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. import numpy as np
  2. from pydub import AudioSegment
  3. from os import listdir, chdir
  4. from os.path import isfile, join
  5. from scipy.fft import *
  6. from scipy.io import wavfile
  7. from termcolor import colored
  8.  
  9. path = "C:\\Users\\HP\\Downloads\\TMF\\TMF-audio\\"
  10. chdir(path)
  11.  
  12. def amplitude(file): #.wav files only
  13.     return AudioSegment.from_wav(path + file).max
  14.  
  15. def duration(file):
  16.     return AudioSegment.from_wav(path + file).duration_seconds*1000
  17.  
  18. def freq(file):
  19.     start_time = 0
  20.     end_time = duration(file)
  21.    
  22.     sr, data = wavfile.read(file)
  23.     if data.ndim > 1:
  24.         data = data[:, 0]
  25.     else:
  26.         pass
  27.  
  28.     dataToRead = data[int(start_time * sr / 1000) : int(end_time * sr / 1000) + 1]
  29.  
  30.     N = len(dataToRead)
  31.     yf = rfft(dataToRead)
  32.     xf = rfftfreq(N, 1 / sr)
  33.  
  34.     idx = np.argmax(np.abs(yf))
  35.     freq = xf[idx]
  36.  
  37.     return round(freq, 2)
  38.  
  39. def get_wav(my_path):
  40.     files = list(f for f in listdir(my_path) if isfile(join(my_path, f)))
  41.     for file in files:
  42.         if not ".wav" in file:
  43.             files.remove(file)
  44.     return files
  45.  
  46. amplitudes = list()
  47. for audio in get_wav(path):
  48.     amplitudes.append(amplitude(audio))
  49.     print(colored((audio + " - " + str(amplitude(audio)) + " dbFS, " + str(freq(audio)) + " Hz"), "green"))
  50. amplitudes.sort()
Add Comment
Please, Sign In to add comment