20. API - Tones¶
from gpiozero.tones import Tone
Represents a frequency of sound in a variety of musical notations.
Toneclass can be used with the
TonalBuzzerclass to easily represent musical tones. The class can be constructed in a variety of ways. For example as a straight frequency in Hz (which is the internal storage format), as an integer MIDI note, or as a string representation of a musical note.
All the following constructors are equivalent ways to construct the typical tuning note, concert A at 440Hz, which is MIDI note #69:
>>> from gpiozero.tones import Tone >>> Tone(440.0) >>> Tone(69) >>> Tone('A4')
If you do not want the constructor to guess which format you are using (there is some ambiguity between frequencies and MIDI notes at the bottom end of the frequencies, from 128Hz down), you can use one of the explicit constructors,
from_note(), or you can specify a keyword argument when constructing:
>>> Tone.from_frequency(440) >>> Tone.from_midi(69) >>> Tone.from_note('A4') >>> Tone(frequency=440) >>> Tone(midi=69) >>> Tone(note='A4')
floatand can be used as a floating point number in most circumstances (addition, subtraction, etc). This part of the API is not yet considered “stable”; i.e. we may decide to enhance / change this behaviour in future versions.
Tonefrom a musical note which must consist of a capital letter A through G, followed by an optional semi-tone modifier (“b” for flat, “#” for sharp, or their Unicode equivalents), followed by an octave number (0 through 9).
For example concert A, the typical tuning note at 440Hz, would be represented as “A4”. One semi-tone above this would be “A#4” or alternatively “Bb4”. Unicode representations of sharp and flat are also accepted.
Return the (nearest) MIDI note to the tone’s frequency. This will be an integer number in the range 0 to 127. If the frequency is outside the range represented by MIDI notes (which is approximately 8Hz to 12.5KHz)
ValueErrorexception will be raised.