Skip to content

Instantly share code, notes, and snippets.

@r4dian
Forked from kroger/convert.py
Last active July 3, 2022 12:13
Show Gist options
  • Save r4dian/4e5146ca298a88822ce88061ffe8cda1 to your computer and use it in GitHub Desktop.
Save r4dian/4e5146ca298a88822ce88061ffe8cda1 to your computer and use it in GitHub Desktop.
Rename wav files using frequency and pitch detection
#!/usr/bin/env python2
import subprocess, os, glob, math
## /!\ Python 2.x /!\
## requires [Aubio](https://aubio.org)
## Rename wav files using frequency and pitch detection:
## GTR_08.wav ---> automated pitch detection & file renaming ---> GTR_08 - C3 (+0cents) - 130.81Hz.wav
WAV_DIR = r"/home/andrewse/"
AUBIO_DIR = r"/usr/bin/"
def get_values(values):
result = []
for line in values.split("\n"):
val = float(line.split()[1]) if line else 0
if val > 0:
result.append(val)
return result
def average(values):
return sum(values)/len(values)
def midi_to_note(midi):
notes = "c c# d d# e f f# g g# a a# b".split()
int_midi = int(round(midi))
pitch = int_midi % 12
letter = notes[pitch]
octaves = "-1 0 1 2 3 4 5 6 7 8 9".split()
oct_no = octaves[int(round(int_midi / 12))]
return letter.upper()+oct_no
def get_freq_and_note(filename):
filename = os.path.join(WAV_DIR, filename)
aubiopitch = os.path.join(AUBIO_DIR, "aubiopitch")
freqs = subprocess.check_output([aubiopitch, "-i", filename])
midis = subprocess.check_output([aubiopitch, "-u", "midi", "-i", filename])
freq = average(get_values(freqs))
note = midi_to_note(average(get_values(midis)))
cents, void = math.modf(average(get_values(midis)))
return freq, note, cents
def rename_file(filename):
freq, note, cents = get_freq_and_note(filename)
newfile = "{0} - {1} (+{3:0.0f}cents)- {2:0.2f}Hz.wav".format("".join(filename.split(".")[:-1]), note, freq, round(cents/100))
full_old = os.path.join(WAV_DIR, filename)
full_new = os.path.join(WAV_DIR, newfile)
print "renaming", newfile
os.rename(full_old, full_new)
for filename in glob.glob("*.wav"):
rename_file(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment