def get_file_bpm(path, params=None): """ Calculate the beats per minute (bpm) of a given file. path: path to the file param: dictionary of parameters """ if params is None: params = {} # default: samplerate, win_s, hop_s = 44100, 1024, 512 if 'mode' in params: if params.mode in ['super-fast']: # super fast samplerate, win_s, hop_s = 4000, 128, 64 elif params.mode in ['fast']: # fast samplerate, win_s, hop_s = 8000, 512, 128 elif params.mode in ['default']: pass else: print("unknown mode {:s}".format(params.mode)) # manual settings if 'samplerate' in params: samplerate = params.samplerate if 'win_s' in params: win_s = params.win_s if 'hop_s' in params: hop_s = params.hop_s s = source(path, samplerate, hop_s) samplerate = s.samplerate o = tempo("specdiff", win_s, hop_s, samplerate) # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) #if o.get_confidence() > .2 and len(beats) > 2.: # break total_frames += read if read < hop_s: break def beats_to_bpm(beats, path): # if enough beats are found, convert to periods then to bpm if len(beats) > 1: if len(beats) < 4: print("few beats found in {:s}".format(path)) bpms = 60./diff(beats) return median(bpms) else: print("not enough beats found in {:s}".format(path)) return 0 return beats_to_bpm(beats, path)
def extract_beats (self): samplerate, win_s, hop_s = 44100, 1024, 512 s = aubio.source('good_test.wav', 44100, 512) o = aubio.tempo("specdiff", self.win_s, self.hop_s, self.rate) self._beats = [] total_frames = 0 i = 0 print "Starting extraction ..." while True: samples = self._waveform [i*self.hop_s:(i+1)*self.hop_s] samples = np.float32(samples) is_beat = o (samples) if is_beat: this_beat = o.get_last_s() print this_beat self._beats.append(this_beat) i += 1 if (i+1)*self.hop_s > len(self._waveform): break #bpms = 60./np.diff(self._beats) print "Beats:" print self._beats print "--- BMP:" b = 60./np.diff(self._beats) self._bpm = np.median(b) print self._bpm
def _initialize_tempo(self): self.tempo_o = aubio.tempo( "default", self._config["fft_size"], self._config["mic_rate"] // self._config["sample_rate"], self._config["mic_rate"], )
def __init__(self, options): self.beat_object = tempo(options.settings['balg'], int(float(options.settings['framesize']) * float(options.settings['bframemult'])), int(float(options.settings['framesize']) * float(options.settings['bframemult']) * float(options.settings['bhopmult'])), int(float(options.settings['samplerate']))) self.frame_arrays = np.zeros( (int(float(options.settings['bframemult'])), int(float(options.settings['framesize']))), dtype=np.float32) self.midi_processor = None self.sysex_command_array = [] for command in options.settings['bsysexnum'].split(' '): self.sysex_command_array.append(int(command, 0)) self.control_number = False if options.settings['bcontrolnum'] != 'None': self.control_number = int(options.settings['bcontrolnum'], 0) self.beat_sequence = [] for item in options.settings['bvaltype'].split(','): self.beat_sequence.append(int(item.strip())) if not self.beat_sequence: self.beat_sequence = [64] self.beat_sequence_position = 0 self.frame_count = 0 self.frame_multiplier = int(options.settings['bframemult'])
def compute_tempo(self, fin, samplerate=44100, win_size=512): """compute song tempo using specdiff estimation. A change in sample rate might affect tempo estimation by approximatively 1 BPM :param str fin: name of the song to analyze :param int samplerate: samplerate to use for tempo analysis. Defaults to 44.1kHz :param int win_size: window size :return int bpm_est: BPM estimation. 0 if beats are too few to perform an analysis (=less than 4) """ s = aubio.source(fin, samplerate, win_size) o = aubio.tempo('specdiff', 1024, win_size, s.samplerate) beats = [] total_frames = 0 log.info('%s: Computing tempo...', fin) while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) total_frames += read if read < 512: break # Convert to periods and to bpm if len(beats) > 1: if len(beats) < 4: # the song is too short to recognize a tempo return 0 bpms = 60. / np.diff(beats) bpm_est = int(round(np.median(bpms))) else: # too few beats to recognize a tempo return 0 duration = int(total_frames / samplerate * 1000) return bpm_est, duration
def get_bpm(song_file): """ Given a passed in file path to an audio file, this method returns the average (median) beats per minute. This method uses the Aubio library, and is very similar to one of the examples here: https://github.com/aubio/aubio/tree/master/python/demos """ samplerate, win_s, hop_s = 44100, 1024, 512 s = aubio.source(song_file, samplerate, hop_s) samplerate = s.samplerate o = aubio.tempo("specdiff", win_s, hop_s, samplerate) beats = [] total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) total_frames += read if read < hop_s: break if len(beats) > 1: bpms = 60./np.diff(beats) median_bpm = np.median(bpms) else: median_bpm = 0 print("No beats found") return median_bpm
def calculate_song_beats(path: str): path = f'{DATA_FOLDER}/{path}' win_s = 512 # fft size hop_s = win_s // 2 # hop size filename = path samplerate = 0 total_frames = 0 s = source(filename, samplerate, hop_s) samplerate = s.samplerate o = tempo("default", win_s, hop_s, samplerate) delay = 4. * hop_s # list of beats beats = [] beats01 = [] while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = int(total_frames - delay + is_beat[0] * hop_s) beats.append(this_beat) beats01.append(this_beat / float(samplerate)) total_frames += read if read < hop_s: break return beats01
def setup(self, channels=None, samplerate=None, blocksize=None, totalframes=None): super(AubioBPM, self).setup(channels, samplerate, blocksize, totalframes) self.win_s = 512 self.hop_s = self.win_s / 2 self.t = tempo("default", self.win_s, self.hop_s, 1) self.block_read = 0 self.beats = []
def getBeatFrame(path): #cite #referencing example code win_s = 512 # fft size hop_s = win_s // 2 # hop size samplerate = 0 filename = path s = source(filename, samplerate, hop_s) samplerate = s.samplerate o = tempo("default", win_s, hop_s, samplerate) # tempo detection delay, in samples # default to 4 blocks delay to catch up with delay = 4. * hop_s # list of beats, in samples beats = [] # total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = roundHalfUp(total_frames - delay + is_beat[0] * hop_s) beats.append(this_beat) total_frames += read if read < hop_s: break return list(map(lambda x: float(x) / samplerate, beats)) # end
def aubio_beat_tracking(filepath, sample_rate, win_s=512): win_s = win_s # fft size hop_s = win_s // 2 # hop size src = aubio.source(filepath, hop_size=hop_s) #print(f"file: {src.uri}, samplerate: {src.samplerate}, channels: {src.channels}, duration: {src.duration/src.samplerate}") o = aubio.tempo("default", win_s, hop_s, sample_rate) # tempo detection delay, in samples # default to 4 blocks delay to catch up with delay = 4. * hop_s # list of beats, in samples beats = [] # total number of frames read total_frames = 0 while True: samples, read = src() is_beat = o(samples) if is_beat: this_beat = int(total_frames - delay + is_beat[0] * hop_s) #print("%f" % (this_beat / float(SAMPLE_RATE))) beats.append(this_beat/sample_rate) total_frames += read if read < hop_s: break bpm = aubio_beats_to_bpm(beats) print(f"INFO - Analysis: Aubio beat detection finished. BPM of song: {bpm}, amount of beats found: {len(beats)}") return beats, bpm
def play_captured(self): samplerate = 44100 n_channels = 1 buffer_size = 512 stream = self._audio.open(format=self.pyaudio_format, channels=n_channels, rate=samplerate, input=True, frames_per_buffer=buffer_size) self.a_tempo = aubio.tempo("default", self.win_s, self.hop_s, samplerate) while True: try: audiobuffer = stream.read(buffer_size) signal = np.fromstring(audiobuffer, dtype=np.float32) is_beat = self.a_tempo(signal) if is_beat: self.__invoke_external_callback() except KeyboardInterrupt: print("*** Ctrl+C pressed, exiting") break
def __init__(self, song, win_s=512, hop_s=256, samplerate=0): # Create source with audio file src = aubio.source(song, samplerate, hop_s) # Reassign samplerate (so as not to be zero) samplerate = src.samplerate # Create tempo detection object tempoDetection = aubio.tempo('default', win_s, hop_s, samplerate) delay = 0 # Tempo detection delay self.beats = [] # Track beats of sample self.totalFrames = 0 # All frames read while True: samples, read = src() beatDetected = tempoDetection(samples) if (beatDetected): currBeat = int(self.totalFrames - delay + beatDetected[0] * hop_s) self.beats.append(currBeat / samplerate) self.totalFrames += read if (read < hop_s): break
def __init__(self): self.redis = redis.StrictRedis(host=redishost, port=6379, password="", decode_responses=True) self.p = pyaudio.PyAudio() stream = self.p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, output=True, input_device_index = self.get_input_device_index(), output_device_index = self.get_output_device_index(), frames_per_buffer = self.CHUNK, stream_callback=self.callback) self.a_onset = aubio.onset("default", self.CHUNK, self.hop_s, self.RATE) self.a_tempo = aubio.tempo("specflux", self.CHUNK, self.hop_s, self.RATE) self.a_pitch = aubio.pitch("default", self.CHUNK, self.hop_s, self.RATE) self.a_notes = aubio.notes("default", self.CHUNK, self.hop_s, self.RATE) n_filters = 40 # required n_coeffs = 13 # I wonder if i made this 1.... self.a_pvoc = aubio.pvoc(self.CHUNK, self.hop_s) self.a_mfcc = aubio.mfcc(self.CHUNK, n_filters, n_coeffs, self.RATE) self.tolerance = 0.8 self.a_pitch.set_tolerance(self.tolerance) self.highest_pitch = 0 self.lowest_pitch = 99999999 self.average_pitch = 0 self.average_pitch_samples = 0 self.last_average = 0 self.colors = None self.pitch_range = None self.range_counter = 0 self.all_notes = set() stream.start_stream()
def get_tempo(filein): win_s = 512 # fft size hop_s = win_s // 2 # hop size filename = filein samplerate = 0 s = source(filename, samplerate, hop_s) samplerate = s.samplerate tempo_o = tempo("default", win_s, hop_s, samplerate) # tempo detection delay, in samples # default to 4 blocks delay to catch up with delay = 4. * hop_s beats = [] bpm = [] # total number of frames read total_frames = 0 while True: samples, read = s() is_beat = tempo_o(samples) if is_beat: this_beat = int(total_frames - delay + is_beat[0] * hop_s) beats.append(this_beat) bpm.append(tempo_o.get_bpm()) total_frames += read if read < hop_s: break return np.array(bpm)
def getBmp(path, params={}): try: win_s = params['win_s'] samplerate = params['samplerate'] hop_s = params['hop_s'] except: #default: samplerate, win_s, hop_s = 44100, 1024, 512 s = source(path, samplerate, hop_s) samplerate = s.samplerate o = tempo("specdiff", win_s, hop_s, samplerate) #list of beats, in samples beats = [] #Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) total_frames += read if read < hop_s: break bpms = 60./np.diff(beats) b = np.median(bpms) return b
def __init__(self, options): self.tempo_object = tempo(options.settings['talg'], int(float(options.settings['framesize']) * float(options.settings['tframemult'])), int(float(options.settings['framesize']) * float(options.settings['tframemult']) * float(options.settings['thopmult'])), int(float(options.settings['samplerate']))) self.frame_arrays = np.zeros( (int(float(options.settings['tframemult'])), int(float(options.settings['framesize']))), dtype=np.float32) self.midi_processor = None self.sysex_command_array = [] for command in options.settings['tsysexnum'].split(' '): self.sysex_command_array.append(int(command, 0)) self.bpm_sysex_rule = self.bpm_to_two_bytes if options.settings['tsysextype'] == 'twobytes': self.bpm_sysex_rule = self.bpm_to_two_bytes elif options.settings['tsysextype'] == 'minus60': self.bpm_sysex_rule = self.bpm_minus_sixty self.control_number = False if options.settings['tcontrolnum'] != 'None': self.control_number = int(options.settings['tcontrolnum'], 0) self.bpm_control_rule = self.bpm_minus_sixty if options.settings['tcontroltype'] == 'minus60': self.bpm_control_rule = self.bpm_minus_sixty self.frame_count = 0 self.BPMs = [] self.average_BPMs = [] self.last_BPM = 0.0 self.average = int(options.settings['taverage']) self.count = int(options.settings['tcount']) self.frame_multiplier = int(options.settings['tframemult'])
def __init__(self, audio_file): self.audio_file = audio_file self.audio_file_wav = self.audio_file.split(MP3_AUDIO_EXT)[0] self._convert_to_wav() self.s = source(self.audio_file_wav + WAV_AUDIO_EXT, 0, self.HOP_S) self.o = tempo("default", self.WIN_S, self.HOP_S, self.s.samplerate) self._beats = []
def initializeAudio(self): global file # opens file as wave file self.src = file + ".wav" samplerate = 0 self.total_frames = 0 # initialize aubio data self.a_source = aubio.source(self.src, samplerate, self.hop_s) self.samplerate = self.a_source.samplerate self.p = pyaudio.PyAudio() self.format = pyaudio.paFloat32 self.frames = self.hop_s self.channels = 1 self.p = pyaudio.PyAudio() self.a_tempo = aubio.tempo("default", self.win_s, self.hop_s, self.samplerate) self.pitch_o = aubio.pitch("yin", self.win_s, self.hop_s, self.samplerate) self.notes_o = aubio.notes("default", self.win_s, self.hop_s, self.samplerate) self.o = aubio.onset("default", self.win_s, self.hop_s, self.samplerate) self.o2 = aubio.onset("hfc", self.win_s, self.hop_s, self.samplerate) print("Audio set up for", file)
def __init__(self, win_size=512, samplerate=44100): # total number of audio frames read self._total_frames = 0 # list of beats, in seconds since start self._beats = [] # recording window and hop size self._win_size = win_size self._hop_size = win_size // 2 # hop size # audio sample rate self._samplerate = samplerate # tempo finder algorithm instance self._tempo_alg = tempo("default", self._win_size, self._hop_size, self._samplerate) logging.info("Tempo silence=%d" % self._tempo_alg.get_silence()) self._tempo_alg.set_silence(-40) self.on_pause = False # pitch algorithm instance # self.pitch_alg = pitch("default", self.win_size, self.hop_size, self.samplerate) self._mono_vec = numpy.array([], dtype=numpy.float32) self._tempo_found_callback = TempoFinder.default_tempo_found_callback self._starting_millis = time() * 1000. self._stream = sounddevice.InputStream( channels=1, samplerate=float(self._samplerate), dtype='float32', latency='low', callback=self.audio_callback) if WRITE_WAV: self._out_file = sink(samplerate=int(self._samplerate))
def get_file_bpm(path, params=None): """ Calculate the beats per minute (bpm) of a given file. path: path to the file param: dictionary of parameters """ if params is None: params = {} # default: samplerate, win_s, hop_s = 44100, 1024, 512 if 'mode' in params: if params.mode in ['super-fast']: # super fast samplerate, win_s, hop_s = 4000, 128, 64 elif params.mode in ['fast']: # fast samplerate, win_s, hop_s = 8000, 512, 128 elif params.mode in ['default']: pass else: raise ValueError("unknown mode {:s}".format(params.mode)) # manual settings if 'samplerate' in params: samplerate = params.samplerate if 'win_s' in params: win_s = params.win_s if 'hop_s' in params: hop_s = params.hop_s s = source(path, samplerate, hop_s) samplerate = s.samplerate o = tempo("specdiff", win_s, hop_s, samplerate) # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) #if o.get_confidence() > .2 and len(beats) > 2.: # break total_frames += read if read < hop_s: break def beats_to_bpm(beats, path): # if enough beats are found, convert to periods then to bpm if len(beats) > 1: if len(beats) < 4: print("few beats found in {:s}".format(path)) bpms = 60. / diff(beats) return median(bpms) else: print("not enough beats found in {:s}".format(path)) return 0 return beats_to_bpm(beats, path)
def find_beats(filename): win_s = 512 # fft size hop_s = win_s // 2 # hop size samplerate = 0 source = aubio.source(filename, samplerate, hop_s) samplerate = source.samplerate # print(source) # print(source.samplerate) # print(source.duration) # print(source.duration/source.samplerate) # print(source.channels) # #print(source.__dir__()) tempo = aubio.tempo("default", win_s, hop_s, samplerate) delay = 4. * hop_s beats = [] # total number of frames read total_frames = 0 while True: samples, read = source() is_beat = tempo(samples) if is_beat: this_beat = int(total_frames - delay + is_beat[0] * hop_s) beats.append(int(100 * this_beat / source.samplerate)) total_frames += read if read < hop_s: break return beats
def tempo_ext(filename): win_s = 512 # fft size hop_s = win_s / 2 # hop size samplerate = 11000 s = source(filename, samplerate, hop_s) samplerate = s.samplerate o = tempo("default", win_s, hop_s, samplerate) # tempo detection delay, in samples # default to 4 blocks delay to catch up with delay = 4.0 * hop_s # list of beats, in samples beats = [] # total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = int(total_frames - delay + is_beat[0] * hop_s) # print "%f" % (this_beat / float(samplerate)) beats.append(this_beat) total_frames += read if read < hop_s: break # convert samples to seconds beats = map(lambda x: x / float(samplerate), beats) bpms = [60.0 / (b - a) for a, b in zip(beats[:-1], beats[1:])] print "BPM: ", median(bpms) * 4
def get_file_bpm(self, path): """ Calculate the beats per minute (bpm) of a given file. path: path to the file buf_size length of FFT hop_size number of frames between two consecutive runs samplerate sampling rate of the signal to analyze """ samplerate, buf_size, hop_size = bpm_slider_settings[ BPMOptionsPage.config.setting["bpm_slider_parameter"]] mediasource = source(path.encode("utf-8"), samplerate, hop_size) samplerate = mediasource.samplerate beattracking = tempo("specdiff", buf_size, hop_size, samplerate) # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = mediasource() is_beat = beattracking(samples) if is_beat: this_beat = beattracking.get_last_s() beats.append(this_beat) total_frames += read if read < hop_size: break # Convert to periods and to bpm bpms = 60. / diff(beats) return median(bpms)
def _get_bpm(self): o = tempo("specdiff", self._win_size, self._hop_size, self._samplerate) # List of beats, in samples if self._stereo: samples = self._get_samples(self._wav_array, 'L+R').astype(np.float32) else: samples = self._get_samples(self._wav_array, 'Mono').astype(np.float32) beats = [] steps = len(samples) - (len(samples) % self._hop_size) for i in range(0, steps, self._hop_size): samples_proc = samples[i:i + self._hop_size] is_beat = o(samples_proc) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) # Convert to periods and to bpm if len(beats) > 1: if len(beats) < 4: print("few beats found in wave array") bpms = 120. / np.diff(beats) b = np.median(bpms) if b > 200: while b > 200: b /= 2 else: b = 0 print("not enough beats found in wave array") b = round(b) if int(b) & 1: b -= 1 return b
def __init__(self, filename, samplerate): self.beats = [] self.win_s = 1024 # fft size self.hop_s = self.win_s // 2 self.filename = filename self.samplerate = samplerate self.a_source = aubio.source(self.filename, self.samplerate, self.hop_s) self.samplerate = self.a_source.samplerate self.pyaudioFlag = [True] # create aubio tempo detection # self.a_tempo = aubio.tempo("default", self.win_s, self.hop_s, self.samplerate) self.spec_tempo = aubio.tempo( "specdiff", self.win_s, self.hop_s, self.samplerate) #spectral difference method
def _aubio(path: str, params=None) -> float: """Using aubio to calculate the bpm of a given files. This function is copied from the example files of aubio and could be found here: https://github.com/aubio/aubio/blob/master/python/demos/demo_bpm_extract.py The arguments are: path: path to the file param: dictionary of parameters """ if params is None: params = {} # default: samplerate, win_s, hop_s = 44100, 1024, 512 if "mode" in params: if params.mode in ["super-fast"]: # super fast samplerate, win_s, hop_s = 4000, 128, 64 elif params.mode in ["fast"]: # fast samplerate, win_s, hop_s = 8000, 512, 128 elif params.mode in ["default"]: pass else: raise ValueError("unknown mode {:s}".format(params.mode)) # manual settings if "samplerate" in params: samplerate = params.samplerate if "win_s" in params: win_s = params.win_s if "hop_s" in params: hop_s = params.hop_s s = aubio.source(path, samplerate, hop_s) samplerate = s.samplerate o = aubio.tempo("specdiff", win_s, hop_s, samplerate) # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) # if o.get_confidence() > .2 and len(beats) > 2.: # break total_frames += read if read < hop_s: break return BPM._beats_to_bpm(beats, path)
def getFileBpm(self, path, params=None): try: with NamedTemporaryFile("w+b", suffix=".wav") as tmpFile: song = AudioSegment.from_file(path, DirectoryTools.getFileType(path)) song.export(tmpFile.name, format="wav") #""" Calculate the beats per minute (bpm) of a given file. #path: path to the file #param: dictionary of parameters #""" if params is None: params = {} try: win_s = params['win_s'] samplerate = params['samplerate'] hop_s = params['hop_s'] except KeyError: """ # super fast samplerate, win_s, hop_s = 4000, 128, 64 # fast samplerate, win_s, hop_s = 8000, 512, 128 """ # default: samplerate, win_s, hop_s = 44100, 1024, 512 s = source(tmpFile.name, samplerate, hop_s) samplerate = s.samplerate o = tempo("specdiff", win_s, hop_s, samplerate) # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) #if o.get_confidence() > .2 and len(beats) > 2.: # break total_frames += read if read < hop_s: break # Convert to periods and to bpm if len(beats) > 1: if len(beats) < 4: print("few beats found in {:s}".format(path)) bpms = 60. / diff(beats) b = median(bpms) else: b = 0 print("not enough beats found in {:s}".format(path)) return b except Exception: return 0
def setup(self, channels=None, samplerate=None, blocksize=None, totalframes=None): super(AubioTemporal, self).setup(channels, samplerate, blocksize, totalframes) self.o = onset("default", self.input_blocksize, self.input_stepsize, samplerate) self.t = tempo("default", self.input_blocksize, self.input_stepsize, samplerate) self.block_read = 0 self.onsets = [] self.beats = [] self.beat_confidences = []
def __init__(self, config): super().__init__(config) self.epoch = time.time() self.last_beat = 0 self.next_beat = 0 self.tempo = aubio.tempo("default", self.config.fftSize, self.config.bufferSize, self.config.sampleRate)
def calculate_song_bpm(path: str, params: typing.Dict = None): path = f'{DATA_FOLDER}/{path}' if params is None: params = {} # default: samplerate, win_s, hop_s = 44100, 1024, 512 if 'mode' in params: if params.mode in ['super-fast']: # super fast samplerate, win_s, hop_s = 4000, 128, 64 elif params.mode in ['fast']: # fast samplerate, win_s, hop_s = 8000, 512, 128 elif params.mode in ['default']: pass else: print("unknown mode {:s}".format(params.mode)) # manual settings if 'samplerate' in params: samplerate = params.samplerate if 'win_s' in params: win_s = params.win_s if 'hop_s' in params: hop_s = params.hop_s s = source(path, samplerate, hop_s) samplerate = s.samplerate o = tempo("specdiff", win_s, hop_s, samplerate) # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) #if o.get_confidence() > .2 and len(beats) > 2.: # break total_frames += read if read < hop_s: break def beats_to_bpm(beats, path): if len(beats) > 1: if len(beats) < 4: print("few beats found in {:s}".format(path)) bpms = 60. / diff(beats) #bpm is an array medinbpm = median(bpms) #medinbpm is a float number return medinbpm #needs to be understood else: print("not enough beats found in {:s}".format(path)) return 0 # print "beats-in-bpm: ", beats return beats_to_bpm(beats, path)
def __init__(self, channels, samplerate, cfg_fps): hop_s = samplerate // cfg_fps * channels # hop size win_s = hop_s * 2 # fft size import aubio # create aubio tempo detection self.a_tempo = aubio.tempo("default", win_s, hop_s, samplerate) self.hop_s = hop_s
def play(file_name, handle_beat, sample_rate=0): win_s = 1024 # fft size hop_s = win_s // 2 # hop size a_source = aubio.source(file_name, sample_rate, hop_s) # create aubio source sample_rate = a_source.samplerate # create aubio tempo detection a_tempo = aubio.tempo("default", win_s, hop_s, sample_rate) global last_beat_time last_beat_time = time.time() # pyaudio callback def callback(_in_data, _frame_count, _time_info, _status): samples, read = a_source() is_beat = a_tempo(samples) global last_beat_time now = time.time() if is_beat: beat_length = now - last_beat_time last_beat_time = now print("tick") t = threading.Thread(target=handle_beat, args=[beat_length]) t.start() audiobuf = samples.tobytes() if read < hop_s: beat_length = now - last_beat_time handle_beat(beat_length) #t = threading.Thread(target=handle_beat, args=[beat_length]) #t.start() return audiobuf, pyaudio.paComplete return audiobuf, pyaudio.paContinue # create pyaudio stream with frames_per_buffer=hop_s and format=paFloat32 p = pyaudio.PyAudio() pyaudio_format = pyaudio.paFloat32 frames_per_buffer = hop_s n_channels = 1 stream = p.open(format=pyaudio_format, channels=n_channels, rate=sample_rate, output=True, frames_per_buffer=frames_per_buffer, stream_callback=callback) # start pyaudio stream stream.start_stream() # wait for stream to finish while stream.is_active(): time.sleep(0.1) # stop pyaudio stream stream.stop_stream() stream.close() # close pyaudio p.terminate()
def __init__(self, config): super().__init__(config) self.config = self.config.get('Beat', {}) self.win_s = 1024 self.hop_s = self.frames_per_buffer = int( self.capconfig['SampleRate'] / self.capconfig['FPS']) self.onset_detect = aubio.onset('energy', self.win_s, self.hop_s, self.capconfig['SampleRate']) self.beat_detect = aubio.tempo('hfc', self.win_s, self.hop_s, self.capconfig['SampleRate'])
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fps = FPSCounter('Beat Processor') self.win_s = 1024 self.hop_s = self.frames_per_buffer = int(self.config['MIC_RATE'] / self.config['FPS']) self.onset_detect = aubio.onset('energy', self.win_s, self.hop_s, self.config['MIC_RATE']) self.beat_detect = aubio.tempo('hfc', self.win_s, self.hop_s, self.config['MIC_RATE'])
def audio_init(self, source, samplerate, win_s, hop_s): #pyaudio init. self.audio = pyaudio.PyAudio() self.audio_format = pyaudio.paFloat32 self.fpb = hop_s n_channels = 1 ## well, one line of ros logic here self.r = rospy.Rate(RATE // win_s) # 50 Hz # initialize ros beat_msgs self.msg=Beat() self.msg = Beat() self.msg.beat = True # select aubio source if (source == "live"): # or source print("Tapping to the live input") self.mode = BeatMaker.LIVE samplerate = RATE self.btempo = aubio.tempo("default", win_s, hop_s, samplerate) self.stream = self.audio.open(format=self.audio_format, channels=n_channels, rate=samplerate, input=True, frames_per_buffer=self.fpb, stream_callback=self.mic_callback) else: print("Tapping to the audio file") self.mode = BeatMaker.OFFLINE self.source = aubio.source(source, samplerate, hop_s) samplerate = self.source.samplerate self.btempo = aubio.tempo("default", win_s, hop_s, samplerate) self.stream = self.audio.open(format=self.audio_format, channels=n_channels, rate=samplerate, output=True, frames_per_buffer=self.fpb, stream_callback=self.file_callback) self.click = 0.7 * np.sin( 2. * np.pi * np.arange(hop_s) / hop_s * samplerate / 3000.)
def get_file_bpm(path, params = None): """ Calculate the beats per minute (bpm) of a given file. path: path to the file param: dictionary of parameters """ if params is None: params = {} try: win_s = params['win_s'] samplerate = params['samplerate'] hop_s = params['hop_s'] except KeyError: """ # super fast samplerate, win_s, hop_s = 4000, 128, 64 # fast samplerate, win_s, hop_s = 8000, 512, 128 """ # default: samplerate, win_s, hop_s = 44100, 1024, 512 s = source(path, samplerate, hop_s) samplerate = s.samplerate o = tempo("specdiff", win_s, hop_s, samplerate) # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) #if o.get_confidence() > .2 and len(beats) > 2.: # break total_frames += read if read < hop_s: break # Convert to periods and to bpm if len(beats) > 1: if len(beats) < 4: print("few beats found in {:s}".format(path)) bpms = 60./diff(beats) for element in bpms: print element bpms2.append(bpms) b = median(bpms) else: b = 0 print("not enough beats found in {:s}".format(path)) return b
def play_music(filename, handle_beat, samplerate=0): win_s = 1024 # fft size hop_s = win_s // 2 # hop size #samplerate = 0 #if len(sys.argv) > 2: samplerate = int(sys.argv[2]) # create aubio source a_source = aubio.source(filename, samplerate, hop_s) samplerate = a_source.samplerate # create aubio tempo detection a_tempo = aubio.tempo("default", win_s, hop_s, samplerate) # create a simple click sound click = 0.7 * np.sin( 2. * np.pi * np.arange(hop_s) / hop_s * samplerate / 3000.) # pyaudio callback def pyaudio_callback(_in_data, _frame_count, _time_info, _status): samples, read = a_source() is_beat = a_tempo(samples) if is_beat: #samples += click handle_beat() audiobuf = samples.tobytes() if read < hop_s: return (audiobuf, pyaudio.paComplete) return (audiobuf, pyaudio.paContinue) # create pyaudio stream with frames_per_buffer=hop_s and format=paFloat32 p = pyaudio.PyAudio() pyaudio_format = pyaudio.paFloat32 frames_per_buffer = hop_s n_channels = 1 stream = p.open(format=pyaudio_format, channels=n_channels, rate=samplerate, output=True, frames_per_buffer=frames_per_buffer, stream_callback=pyaudio_callback) # start pyaudio stream stream.start_stream() # wait for stream to finish while stream.is_active(): time.sleep(0.1) # stop pyaudio stream stream.stop_stream() stream.close() stream.get # close pyaudio p.terminate()
def setup(self, channels=None, samplerate=None, blocksize=None, totalframes=None): super(AubioTemporal, self).setup(channels, samplerate, blocksize, totalframes) self.o = onset("default", self.input_blocksize, self.input_stepsize, samplerate) self.t = tempo("default", self.input_blocksize, self.input_stepsize, samplerate)
def get_file_bpm(path, params = None): """ Calculate the beats per minute (bpm) of a given file. path: path to the file param: dictionary of parameters """ if params is None: params = {} try: win_s = params['win_s'] samplerate = params['samplerate'] hop_s = params['hop_s'] except KeyError: """ # super fast samplerate, win_s, hop_s = 4000, 128, 64 # fast samplerate, win_s, hop_s = 8000, 512, 128 """ # default: samplerate, win_s, hop_s = 44100, 1024, 512 s = source(path, samplerate, hop_s) samplerate = s.samplerate o = tempo("specdiff", win_s, hop_s, samplerate) # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) #if o.get_confidence() > .2 and len(beats) > 2.: # break total_frames += read if read < hop_s: break # Convert to periods and to bpm if len(beats) > 1: if len(beats) < 4: print("few beats found in {:s}".format(path)) bpms = 60./diff(beats) b = median(bpms) else: b = 0 print("not enough beats found in {:s}".format(path)) return b
def BPM(self, path, param): """ Calculate the beats per minute (bpm) as a rhythm feature. path: path to the file param: dictionary of parameters """ try: win_s = param['wfft'] samplerate = param['sample_rate'] except: win_s = 512 # fft size samplerate = 11000 hop_s = win_s / 2 # hop size s = source(path, samplerate, hop_s) samplerate = s.samplerate o = tempo("default", win_s, hop_s, samplerate) # Tempo detection delay, in samples # default to 4 blocks delay to catch up with delay = 4. * hop_s # List of beats, in samples beats = [] # Total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = int(total_frames - delay + is_beat[0] * hop_s) beats.append(this_beat) total_frames += read if read < hop_s: break # Convert samples to seconds beats = map(lambda x: x/float(samplerate), beats) bpms = [60./(b-a) for a, b in zip(beats[:-1], beats[1:])] if samplerate == 11000: b = median(bpms)*4 elif samplerate == 22000: b = median(bpms)*2 else: b = median(bpms) return b
def bpm(self,path,param): try: win_s = param['wfft'] samplerate = param['sampe_rate'] except: win_s = 512 # fft size samplerate = 11000 hop_s = win_s / 2 # hop size s = source(path, samplerate, hop_s) samplerate = s.samplerate o = tempo("default", win_s, hop_s, samplerate) # tempo detection delay, in samples # default to 4 blocks delay to catch up with delay = 4. * hop_s # list of beats, in samples beats = [] # total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = int(total_frames - delay + is_beat[0] * hop_s) #print "%f" % (this_beat / float(samplerate)) beats.append(this_beat) total_frames += read if read < hop_s: break #convert samples to seconds beats = map( lambda x: x / float(samplerate), beats) bpms = [60./(b - a) for a,b in zip(beats[:-1],beats[1:])] if samplerate == 11000: b = median(bpms)*4 elif samplerate == 22000: b = median(bpms)*2 else: b = median(bpms) return b
def _cut_analyze(options): hopsize = options.hop_size bufsize = options.buf_size samplerate = options.samplerate source_uri = options.source_uri # analyze pass from aubio import onset, tempo, source s = source(source_uri, samplerate, hopsize) if samplerate == 0: samplerate = s.samplerate options.samplerate = samplerate if options.beat: o = tempo(options.onset_method, bufsize, hopsize, samplerate=samplerate) else: o = onset(options.onset_method, bufsize, hopsize, samplerate=samplerate) if options.minioi: if options.minioi.endswith('ms'): o.set_minioi_ms(int(options.minioi[:-2])) elif options.minioi.endswith('s'): o.set_minioi_s(int(options.minioi[:-1])) else: o.set_minioi(int(options.minioi)) o.set_threshold(options.threshold) timestamps = [] total_frames = 0 while True: samples, read = s() if o(samples): timestamps.append(o.get_last()) if options.verbose: print("%.4f" % o.get_last_s()) total_frames += read if read < hopsize: break del s return timestamps, total_frames
def __init__(self, sample_rate=None, buffersize=None): self.sample_rate = sample_rate or self.sample_rate self.buffersize = buffersize or self.buffersize self.window_size = self.buffersize * 2 self.stream = None self.onset = aubio.onset( 'specflux', self.window_size, self.buffersize, self.sample_rate) self.onset.set_threshold(0.3) self.onset.set_silence(-20.) self.tempo = aubio.tempo( 'default', self.window_size, self.buffersize, self.sample_rate) self.energy = aubio.specdesc('specflux', self.buffersize * 2) self.pv = aubio.pvoc(self.buffersize * 2, self.buffersize) self.pitch = aubio.pitch( "yinfft", self.window_size, self.buffersize, self.sample_rate) self.pitch.set_unit("midi") self.pitch.set_tolerance(0.8) self.py_audio = pyaudio.PyAudio()
def extract_bpm(filename): samplerate, win_s, hop_s = RATE, CHUNK, 512 s = source(filename, samplerate, hop_s) o = tempo("specdiff", win_s, hop_s, samplerate) beats = [] total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s() beats.append(this_beat) total_frames += read if read < hop_s: break bpms = 60./numpy.diff(beats) b = numpy.median(bpms) return b
downsample = 1 samplerate = 44100 / downsample if len( sys.argv ) > 2: samplerate = int(sys.argv[2]) win_s = 4096 #/ downsample # fft size hop_s = 512 #/ downsample # hop size T = Map() T.beats = [] T.win_s = 512 # fft size T.hop_s = T.win_s / 2 T.delay = 4. * T.hop_s T.tempo = tempo("default", T.win_s, T.hop_s, samplerate) T.median_win_s = 10 # s = source(filename, samplerate, hop_s) samplerate = 44100#s.samplerate tolerance = 0.8 pitch_o = pitch( "yinfft", win_s, hop_s, samplerate) pitch_o.set_unit("midi") pitch_o.set_tolerance(tolerance) pitches = [] confidences = [] pp=[]
win_s = 512 # fft size hop_s = win_s // 2 # hop size if len(sys.argv) < 2: print("Usage: %s <filename> [samplerate]" % sys.argv[0]) sys.exit(1) filename = sys.argv[1] samplerate = 0 if len( sys.argv ) > 2: samplerate = int(sys.argv[2]) s = source(filename, samplerate, hop_s) samplerate = s.samplerate o = tempo("default", win_s, hop_s, samplerate) # tempo detection delay, in samples # default to 4 blocks delay to catch up with delay = 4. * hop_s # list of beats, in samples beats = [] # total number of frames read total_frames = 0 while True: samples, read = s() is_beat = o(samples) if is_beat: this_beat = o.get_last_s()
#! /usr/bin/python import sys from os.path import splitext, basename from aubio import tempo from aubioinput import aubioinput win_s = 512 # fft size hop_s = win_s / 2 # hop size beat = tempo("default", win_s, hop_s) beats = [] def process(samples, pos): isbeat = beat(samples) if isbeat: thisbeat = (float(isbeat[0]) + pos * hop_s) / 44100. print thisbeat beats.append (thisbeat) if len(sys.argv) < 2: print "Usage: %s <filename>" % sys.argv[0] else: filename = sys.argv[1] a = aubioinput(filename, process = process, hopsize = hop_s, caps = 'audio/x-raw-float, rate=44100, channels=1') a.run()
# parse command line arguments if len(sys.argv) < 2: print("Usage: %s <filename> [samplerate]" % sys.argv[0]) sys.exit(1) filename = sys.argv[1] samplerate = 0 if len( sys.argv ) > 2: samplerate = int(sys.argv[2]) # create aubio source a_source = aubio.source(filename, samplerate, hop_s) samplerate = a_source.samplerate # create aubio tempo detection a_tempo = aubio.tempo("default", win_s, hop_s, samplerate) # create a simple click sound click = 0.7 * np.sin(2. * np.pi * np.arange(hop_s) / hop_s * samplerate / 3000.) # pyaudio callback def pyaudio_callback(_in_data, _frame_count, _time_info, _status): samples, read = a_source() is_beat = a_tempo(samples) if is_beat: samples += click #print ('tick') # avoid print in audio callback audiobuf = samples.tobytes() if read < hop_s: return (audiobuf, pyaudio.paComplete) return (audiobuf, pyaudio.paContinue)
def _parse_(self, filename, samplerate): from aubio import source, pitch, tempo s = source(filename, samplerate, self.hop_s) pitch_o = pitch("default", self.win_s, self.hop_s, samplerate) pitch_o.set_unit("midi") tempo_win_s = self.win_s / 2 tempo_hop_s = self.hop_s / 2 s2 = source(filename, samplerate, tempo_hop_s) tempo_o = tempo("default", tempo_win_s, tempo_hop_s, samplerate) delay = 4. * tempo_hop_s notes = [] # total number of frames read total_frames = 0 samplerate = float(samplerate) previous_samples = [] read = self.hop_s while read >= self.hop_s: samples, read = s() pitch = pitch_o(samples)[0] # go through the finer steps for beat detection for iter in xrange(self.hop_s/tempo_hop_s): samples2, read2 = s2() # if no more stuff to read if read < tempo_hop_s: break # hopefully this work is_beat = tempo_o(samples2) # BUG: doesn't work if sample starts on beat FIRST if is_beat: this_beat = int(total_frames - delay + is_beat[0] * tempo_hop_s) average = sum(previous_samples)/len(previous_samples) note, octave = SimpleConverter.MusicalNote.coord_to_note(average) notes += [(note, octave, total_frames/samplerate)] previous_samples = [] break # don't want to add otherwise because higher chance at transition zone if abs(pitch) > 0.1: previous_samples += [pitch] total_frames += read # BUG: will crash if list is empty current = notes[0] newnotes = [] for i in xrange(1,len(notes)): if current[0] != notes[i][0] or current[1] != notes[i][1]: newnotes += [notes[i]] current = notes[i] notes = newnotes print notes durations = \ SimpleConverter.MusicalNote.get_durations(notes, total_frames / samplerate) (types, eighth_note) = SimpleConverter.MusicalNote.get_types(durations) notes = [SimpleConverter.MusicalNote(notes[i][0] + str(notes[i][1]), types[i]) \ for i in xrange(len(notes))] return notes
if __name__ == '__main__': options, args = parse_args() hopsize = options.hopsize bufsize = options.bufsize samplerate = options.samplerate source_file = options.source_file from aubio import onset, tempo, source, sink s = source(source_file, samplerate, hopsize) if samplerate == 0: samplerate = s.get_samplerate() if options.beat: o = tempo(options.onset_method, bufsize, hopsize) else: o = onset(options.onset_method, bufsize, hopsize) if options.minioi: if options.minioi.endswith('ms'): o.set_minioi_ms(int(options.minioi[:-2])) elif options.minioi.endswith('s'): o.set_minioi_s(int(options.minioi[:-1])) else: o.set_minioi(int(options.minioi)) o.set_threshold(options.threshold) timestamps = [] total_frames = 0 # analyze pass while True:
def __init__(self, args): self.parse_options(args, self.valid_opts) self.tempo = aubio.tempo(**self.options) super(process_beat, self).__init__(args)