Skip to content

Hz2midi

hz2midi

hz2midi(hertz)

Convert a frequency in Hertz to the corresponding MIDI note number.

Validates input to ensure all frequencies are non-negative.

Parameters:

  • hertz (Union[float, list[float]]) –

    The frequency or list of frequencies in Hertz.

Returns:

  • Union[float, list[float]]

    The corresponding MIDI note number or list of numbers (A4 = 440Hz = 69).

Raises:

  • ValueError

    If any frequency is negative.

Examples:

>>> hz2midi(440.0)
69.0
>>> hz2midi([440.0, 880.0])
[69.0, 81.0]
Source code in amads/pitch/hz2midi.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def hz2midi(hertz):
    """
    Convert a frequency in Hertz to the corresponding MIDI note number.

    Validates input to ensure all frequencies are non-negative.

    Parameters
    ----------
    hertz : Union[float, list[float]]
        The frequency or list of frequencies in Hertz.

    Returns
    -------
    Union[float, list[float]]
        The corresponding MIDI note number or list of numbers (A4 = 440Hz = 69).

    Raises
    ------
    ValueError
        If any frequency is negative.

    Examples
    --------
    >>> hz2midi(440.0)
    69.0
    >>> hz2midi([440.0, 880.0])
    [69.0, 81.0]
    """

    def validate_hz(hz):
        if hz < 0:
            raise ValueError(
                f"The frequency of a sound must be non-negative, got {hz}"
            )

    if isinstance(hertz, list):
        for hz in hertz:
            validate_hz(hz)
        return [69 + 12 * math.log2(hz / 440.0) for hz in hertz]
    else:
        validate_hz(hertz)
        return 69 + 12 * math.log2(hertz / 440.0)