# Estimate tempo (BPM) and beat phase of alku.mp3 library(av) info <- av_media_info("alku.mp3") pcm <- read_audio_bin("alku.mp3") ch <- attr(pcm, "channels") m <- matrix(as.numeric(pcm) / 2^31, nrow = ch) x <- colMeans(m) # Downsample 44.1 kHz -> 11.025 kHz by block averaging x <- colMeans(matrix(x[1:(4 * floor(length(x) / 4))], nrow = 4)) sr <- attr(pcm, "sample_rate") / 4 # Spectral-flux onset envelope (hop ~ 11.6 ms) hop <- 128; win <- 1024 n_frames <- floor((length(x) - win) / hop) hann <- 0.5 - 0.5 * cos(2 * pi * (0:(win - 1)) / (win - 1)) prev <- NULL flux <- numeric(n_frames) for (i in seq_len(n_frames)) { seg <- x[((i - 1) * hop + 1):((i - 1) * hop + win)] * hann mag <- log1p(100 * Mod(fft(seg))[1:(win / 2)]) if (!is.null(prev)) flux[i] <- sum(pmax(mag - prev, 0)) prev <- mag } fps_env <- sr / hop flux <- flux - stats::filter(flux, rep(1 / 16, 16), sides = 2) flux[is.na(flux)] <- 0 flux <- pmax(flux, 0) # Autocorrelation over 60-200 BPM, weighted toward ~120 BPM ac <- acf(flux, lag.max = ceiling(fps_env * 1.1), plot = FALSE)$acf[-1] lags <- seq_along(ac) bpm_l <- 60 * fps_env / lags ok <- bpm_l >= 60 & bpm_l <= 200 w <- exp(-0.5 * (log2(bpm_l / 120) / 0.9)^2) best <- lags[ok][which.max((ac * w)[ok])] # Refine with parabolic interpolation y <- ac[(best - 1):(best + 1)] best_f <- best + 0.5 * (y[1] - y[3]) / (y[1] - 2 * y[2] + y[3]) bpm <- 60 * fps_env / best_f # Beat phase: offset that maximises onset energy on the beat grid period <- best_f phases <- seq(0, period, length.out = 200) score <- sapply(phases, function(p) { idx <- round(seq(p, n_frames - 1, by = period)) + 1 sum(flux[idx]) }) offset <- phases[which.max(score)] / fps_env cat(sprintf("duration %.2f s\nBPM %.2f (%.3f beats/s)\nfirst beat %.3f s\n", info$duration, bpm, bpm / 60, offset)) top <- order(-(ac * w)[ok])[1:5] print(data.frame(bpm = round(bpm_l[ok][top], 1), ac = round(ac[ok][top], 3))) saveRDS(list(bpm = bpm, offset = offset, duration = info$duration), "tempo.rds")