fork download
  1. import os
  2. import soundfile
  3. import librosa
  4. import sklearn
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. from scipy.io.wavfile import read, write
  8. from IPython.display import Audio
  9. from numpy.fft import fft, ifft
  10. %matplotlib inline
  11.  
  12. directory = os.fsencode('Kick Drums')
  13. featureSet = np.zeros((5, 1))
  14.  
  15. def extract_features(x, fs, file):
  16. fileName = os.path.split(file)[1]
  17. y, sr = librosa.load(file)
  18. hop_length = 256
  19. frame_length = 512
  20. #zero crossing rate
  21. zcr = librosa.zero_crossings(x).sum()
  22. #energy
  23. energy = np.array([
  24. sum(abs(x[i:i+frame_length]**2))
  25. for i in range(0, len(x), hop_length)
  26. ])
  27. #spectral things
  28. centroid = np.asarray(librosa.feature.spectral_centroid(y=y, sr=sr))
  29. bandwidth = np.asarray(librosa.feature.spectral_bandwidth(y=y, sr=sr))
  30.  
  31. #return np.array([zcr, energy, centroid, bandwidth, fileName])
  32. return np.array([1, [10, 20, 30, 40], [50, 60, 70, 90, 90], 4, fileName])
  33.  
  34. for filename in os.listdir(directory):
  35.  
  36. #doing file things
  37. fileStr = os.path.join(directory, filename)
  38. print(fileStr)
  39. data, samplerate = soundfile.read(fileStr)
  40. #os.remove(fileStr)
  41. soundfile.write(fileStr, data, samplerate, subtype='PCM_16')
  42. x, fs = librosa.load(fileStr)
  43. features = extract_features(x, fs, fileStr)
  44. featureSet = np.column_stack((featureSet, features))
  45.  
  46. for element in featureSet:
  47. if type(element) is np.ndarray:
  48. element = np.transpose(element)
  49. element = *element,
  50.  
  51.  
  52. print(featureSet)
  53. #clustering!
  54. model = sklearn.cluster.KMeans(n_clusters=2)
  55. labels = model.fit_predict(featureSet)
  56. print("pre-labels")
  57. #print(labels)
  58. print("post-labels")
  59.  
Runtime error #stdin #stdout #stderr 0.03s 63152KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
  File "prog.py", line 10
    %matplotlib inline
    ^
SyntaxError: invalid syntax