Skip to main content

autocorrelation_frequency

Function autocorrelation_frequency 

Source
pub fn autocorrelation_frequency(
    signal: &[FloatType],
    sample_rate: FloatType,
) -> Result<FloatType>
Expand description

The frequency a signal sounds, found by autocorrelation: music21’s autocorrelationFunction. The signal’s correlation with itself at each lag is taken; past the first lag where it starts to rise, its highest point, placed between samples by interpolation, is the period. A signal whose correlation never rises is a rest, frequency ten.

music21 correlates with scipy’s FFT convolution, which rounds; the crate sums the products exactly, so the two can differ in the last bits.

use music21_rs::audiosearch::autocorrelation_frequency;

let rate = 44100.0;
let signal: Vec<f64> = (0..1024)
    .map(|i| (2.0 * std::f64::consts::PI * 441.0 * i as f64 / rate).sin() * 10000.0)
    .collect();
let frequency = autocorrelation_frequency(&signal, rate)?;
// music21 finds 442.2033...: the interpolated peak sits a little early.
assert!((frequency - 442.2033).abs() < 1e-3);

§Errors

An empty signal.