more accurate bpm detector

This commit is contained in:
ed 2023-03-31 21:20:37 +00:00
parent 854ba0ec06
commit e7f3e475a2

View file

@ -16,6 +16,10 @@ dep: ffmpeg
""" """
# save beat timestamps to ".beats/filename.txt"
SAVE = False
def det(tf): def det(tf):
# fmt: off # fmt: off
sp.check_call([ sp.check_call([
@ -23,12 +27,11 @@ def det(tf):
b"-nostdin", b"-nostdin",
b"-hide_banner", b"-hide_banner",
b"-v", b"fatal", b"-v", b"fatal",
b"-ss", b"13",
b"-y", b"-i", fsenc(sys.argv[1]), b"-y", b"-i", fsenc(sys.argv[1]),
b"-map", b"0:a:0", b"-map", b"0:a:0",
b"-ac", b"1", b"-ac", b"1",
b"-ar", b"22050", b"-ar", b"22050",
b"-t", b"300", b"-t", b"360",
b"-f", b"f32le", b"-f", b"f32le",
fsenc(tf) fsenc(tf)
]) ])
@ -48,10 +51,29 @@ def det(tf):
return return
# throws if detection failed: # throws if detection failed:
bpm = float(cl[-1]["timestamp"] - cl[1]["timestamp"]) beats = [float(x["timestamp"]) for x in cl]
bpm = round(60 * ((len(cl) - 1) / bpm), 2) bds = [b - a for a, b in zip(beats, beats[1:])]
bds.sort()
n0 = int(len(bds) * 0.2)
n1 = int(len(bds) * 0.75) + 1
bds = bds[n0:n1]
bpm = sum(bds)
bpm = round(60 * (len(bds) / bpm), 2)
print(f"{bpm:.2f}") print(f"{bpm:.2f}")
if SAVE:
fdir, fname = os.path.split(sys.argv[1])
bdir = os.path.join(fdir, ".beats")
try:
os.mkdir(fsenc(bdir))
except:
pass
fp = os.path.join(bdir, fname) + ".txt"
with open(fsenc(fp), "wb") as f:
txt = "\n".join([f"{x:.2f}" for x in beats])
f.write(txt.encode("utf-8"))
def main(): def main():
with tempfile.NamedTemporaryFile(suffix=".pcm", delete=False) as f: with tempfile.NamedTemporaryFile(suffix=".pcm", delete=False) as f: