peterf@2: #!/usr/bin/env python peterf@2: ''' peterf@2: CREATED:2013-02-11 18:37:30 by Brian McFee peterf@2: peterf@2: Track beat events in an audio file peterf@2: peterf@2: Usage: ./beat_tracker.py [-h] input_file.mp3 output_beats.csv peterf@2: ''' peterf@2: from __future__ import print_function peterf@2: peterf@2: import argparse peterf@2: import sys peterf@2: import librosa peterf@2: peterf@2: peterf@2: def beat_track(input_file, output_csv): peterf@2: '''Beat tracking function peterf@2: peterf@2: :parameters: peterf@2: - input_file : str peterf@2: Path to input audio file (wav, mp3, m4a, flac, etc.) peterf@2: peterf@2: - output_file : str peterf@2: Path to save beat event timestamps as a CSV file peterf@2: ''' peterf@2: peterf@2: print('Loading ', input_file) peterf@2: y, sr = librosa.load(input_file, sr=22050) peterf@2: peterf@2: # Use a default hop size of 64 samples @ 22KHz ~= 3ms peterf@2: hop_length = 64 peterf@2: peterf@2: # This is the window length used by default in stft peterf@2: print('Tracking beats') peterf@2: tempo, beats = librosa.beat.beat_track(y=y, sr=sr, hop_length=hop_length) peterf@2: peterf@2: print('Estimated tempo: {:0.2f} beats per minute'.format(tempo)) peterf@2: peterf@2: # save output peterf@2: # 'beats' will contain the frame numbers of beat events. peterf@2: beat_times = librosa.frames_to_time(beats, sr=sr, hop_length=hop_length) peterf@2: peterf@2: print('Saving output to ', output_csv) peterf@2: librosa.output.times_csv(output_csv, beat_times) peterf@2: print('done!') peterf@2: peterf@2: peterf@2: def process_arguments(args): peterf@2: '''Argparse function to get the program parameters''' peterf@2: peterf@2: parser = argparse.ArgumentParser(description='Beat tracking example') peterf@2: peterf@2: parser.add_argument('input_file', peterf@2: action='store', peterf@2: help='path to the input file (wav, mp3, etc)') peterf@2: peterf@2: parser.add_argument('output_file', peterf@2: action='store', peterf@2: help='path to the output file (csv of beat times)') peterf@2: peterf@2: return vars(parser.parse_args(args)) peterf@2: peterf@2: peterf@2: if __name__ == '__main__': peterf@2: # Get the parameters peterf@2: parameters = process_arguments(sys.argv[1:]) peterf@2: peterf@2: # Run the beat tracker peterf@2: beat_track(parameters['input_file'], parameters['output_file'])