Skip to content

Instantly share code, notes, and snippets.

@brihter
Created April 13, 2018 13:46
Show Gist options
  • Save brihter/2c1d70f9a7710264313f3174198f06c1 to your computer and use it in GitHub Desktop.
Save brihter/2c1d70f9a7710264313f3174198f06c1 to your computer and use it in GitHub Desktop.
audio chroma features detection, usage: "python3.6 chroma.py -d data/"
from __future__ import print_function
import sys
import os
import os.path
from os.path import basename
import argparse
import json
import hashlib
import librosa
import librosa.display
import matplotlib.pyplot as plt
from model.track import Track
import codecs, json
# args
parser = argparse.ArgumentParser("processor")
parser.add_argument("-f", help="file to process", type=str, dest="filename")
parser.add_argument("-d", help="directory to process", type=str, dest="directory")
args = parser.parse_args()
filename = args.filename
directory = args.directory
files = []
if directory == None:
files.append(filename)
if filename == None:
for f in os.listdir(directory):
files.append(directory + os.fsdecode(f))
for filename in files:
t1 = Track()
t1.file_hash = hashlib.md5(filename.encode('utf-8')).hexdigest()
t1.file_path = filename
t1.file_name = basename(filename)
target = "out/" + os.path.splitext(t1.file_name)[0] + ".png"
if os.path.exists(target):
print("skipping: " + t1.file_name)
continue
print("processing: " + t1.file_name)
open(target, 'a').close()
# process
y, sr = librosa.load(filename)
t1.r_length = librosa.get_duration(y=y, sr=sr)
onset_env = librosa.onset.onset_strength(y, sr=sr)
y_harm, y_perc = librosa.effects.hpss(y)
chroma = librosa.feature.chroma_cqt(y=y_harm, sr=sr)
# plot and save to file
plt.figure(figsize=(100,8))
librosa.display.specshow(chroma, sr=sr, x_axis='time', y_axis='chroma', vmin=0, vmax=1)
plt.title('Chromagram')
plt.colorbar()
plt.tight_layout()
plt.savefig(target)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment