Skip to content

Commit 5514e30

Browse files
committed
synthio: add midi_to_hz
to convert notes in the MIDI 1-127 note scale to floating point Hz
1 parent bd9aca2 commit 5514e30

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

shared-bindings/synthio/__init__.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,12 +262,19 @@ STATIC mp_obj_t synthio_from_file(size_t n_args, const mp_obj_t *pos_args, mp_ma
262262
}
263263
MP_DEFINE_CONST_FUN_OBJ_KW(synthio_from_file_obj, 1, synthio_from_file);
264264

265+
STATIC mp_obj_t midi_to_hz(mp_obj_t arg) {
266+
mp_int_t note = mp_arg_validate_int_range(mp_obj_get_int(arg), 1, 127, MP_QSTR_note);
267+
return mp_obj_new_float(common_hal_synthio_midi_to_hz_float(note));
268+
}
269+
MP_DEFINE_CONST_FUN_OBJ_1(synthio_midi_to_hz_obj, midi_to_hz);
270+
265271
STATIC const mp_rom_map_elem_t synthio_module_globals_table[] = {
266272
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_synthio) },
267273
{ MP_ROM_QSTR(MP_QSTR_MidiTrack), MP_ROM_PTR(&synthio_miditrack_type) },
268274
{ MP_ROM_QSTR(MP_QSTR_Synthesizer), MP_ROM_PTR(&synthio_synthesizer_type) },
269275
{ MP_ROM_QSTR(MP_QSTR_from_file), MP_ROM_PTR(&synthio_from_file_obj) },
270276
{ MP_ROM_QSTR(MP_QSTR_Envelope), MP_ROM_PTR(&synthio_envelope_type_obj) },
277+
{ MP_ROM_QSTR(MP_QSTR_midi_to_hz), MP_ROM_PTR(&synthio_midi_to_hz_obj) },
271278
};
272279

273280
STATIC MP_DEFINE_CONST_DICT(synthio_module_globals, synthio_module_globals_table);

shared-bindings/synthio/__init__.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,4 @@ extern int16_t shared_bindings_synthio_square_wave[];
3333
extern const mp_obj_namedtuple_type_t synthio_envelope_type_obj;
3434
void synthio_synth_envelope_set(synthio_synth_t *synth, mp_obj_t envelope_obj);
3535
mp_obj_t synthio_synth_envelope_get(synthio_synth_t *synth);
36+
mp_float_t common_hal_synthio_midi_to_hz_float(mp_int_t note);

shared-module/synthio/__init__.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ STATIC const int16_t square_wave[] = {-32768, 32767};
3636
STATIC const uint16_t notes[] = {8372, 8870, 9397, 9956, 10548, 11175, 11840,
3737
12544, 13290, 14080, 14917, 15804}; // 9th octave
3838

39+
mp_float_t common_hal_synthio_midi_to_hz_float(mp_int_t arg) {
40+
uint8_t octave = arg / 12;
41+
uint16_t base_freq = notes[arg % 12];
42+
return MICROPY_FLOAT_C_FUN(ldexp)(base_freq, octave - 10);
43+
}
44+
3945
STATIC int16_t convert_time_to_rate(uint32_t sample_rate, mp_obj_t time_in, int16_t difference) {
4046
mp_float_t time = mp_obj_get_float(time_in);
4147
int num_samples = (int)MICROPY_FLOAT_C_FUN(round)(time * sample_rate);

0 commit comments

Comments
 (0)