3 from aubio import source, tempo
4 from numpy import median, diff
6 def get_file_bpm(path, params=None):
7 """ Calculate the beats per minute (bpm) of a given file.
9 param: dictionary of parameters
14 samplerate, win_s, hop_s = 44100, 1024, 512
16 if params.mode in ['super-fast']:
18 samplerate, win_s, hop_s = 4000, 128, 64
19 elif params.mode in ['fast']:
21 samplerate, win_s, hop_s = 8000, 512, 128
22 elif params.mode in ['default']:
25 print("unknown mode {:s}".format(params.mode))
27 if 'samplerate' in params:
28 samplerate = params.samplerate
34 s = source(path, samplerate, hop_s)
35 samplerate = s.samplerate
36 o = tempo("specdiff", win_s, hop_s, samplerate)
37 # List of beats, in samples
39 # Total number of frames read
46 this_beat = o.get_last_s()
47 beats.append(this_beat)
48 #if o.get_confidence() > .2 and len(beats) > 2.:
54 def beats_to_bpm(beats, path):
55 # if enough beats are found, convert to periods then to bpm
58 print("few beats found in {:s}".format(path))
59 bpms = 60./diff(beats)
62 print("not enough beats found in {:s}".format(path))
65 return beats_to_bpm(beats, path)
67 if __name__ == '__main__':
69 parser = argparse.ArgumentParser()
70 parser.add_argument('-m', '--mode',
71 help="mode [default|fast|super-fast]",
73 parser.add_argument('sources',
76 args = parser.parse_args()
77 for f in args.sources:
78 bpm = get_file_bpm(f, params = args)
79 print("{:6s} {:s}".format("{:2f}".format(bpm), f))