|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2025 Tim Cocks for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +import adafruit_midi |
| 6 | +import adafruit_tlv320 |
| 7 | +import audiobusio |
| 8 | +import board |
| 9 | +import synthio |
| 10 | +import usb.core |
| 11 | +from adafruit_midi.note_off import NoteOff |
| 12 | +from adafruit_midi.note_on import NoteOn |
| 13 | +from displayio import release_displays |
| 14 | +from pwmio import PWMOut |
| 15 | + |
| 16 | +import adafruit_usb_host_midi |
| 17 | + |
| 18 | +release_displays() |
| 19 | +print("Looking for midi device") |
| 20 | +raw_midi = None |
| 21 | +while raw_midi is None: |
| 22 | + for device in usb.core.find(find_all=True): |
| 23 | + try: |
| 24 | + raw_midi = adafruit_usb_host_midi.MIDI(device, timeout=0.01) |
| 25 | + print("Found", hex(device.idVendor), hex(device.idProduct)) |
| 26 | + except ValueError: |
| 27 | + continue |
| 28 | + |
| 29 | + |
| 30 | +mclk_pwm = PWMOut(board.I2S_MCLK, frequency=15_000_000, duty_cycle=2**15) |
| 31 | + |
| 32 | +i2c = board.I2C() |
| 33 | +dac = adafruit_tlv320.TLV320DAC3100(i2c) |
| 34 | + |
| 35 | +# set sample rate & bit depth, use bclk |
| 36 | +dac.configure_clocks(sample_rate=44100, bit_depth=16, mclk_freq=15_000_000) |
| 37 | + |
| 38 | +# use headphones |
| 39 | +dac.headphone_output = True |
| 40 | +dac.dac_volume = -5 # dB |
| 41 | +dac.headphone_volume = -30 |
| 42 | +audio = audiobusio.I2SOut(board.I2S_BCLK, board.I2S_WS, board.I2S_DIN) |
| 43 | + |
| 44 | +synth = synthio.Synthesizer(sample_rate=44100) |
| 45 | +audio.play(synth) |
| 46 | + |
| 47 | +midi = adafruit_midi.MIDI(midi_in=raw_midi, in_channel=0) |
| 48 | + |
| 49 | +pressed = {} |
| 50 | + |
| 51 | +while True: |
| 52 | + msg = midi.receive() |
| 53 | + if isinstance(msg, NoteOn) and msg.velocity != 0: |
| 54 | + note = synthio.Note(synthio.midi_to_hz(msg.note)) |
| 55 | + print("noteOn: ", msg.note, "vel:", msg.velocity) |
| 56 | + synth.press(note) |
| 57 | + pressed[msg.note] = note |
| 58 | + elif ( |
| 59 | + isinstance(msg, NoteOff) or (isinstance(msg, NoteOn) and msg.velocity == 0) |
| 60 | + ) and msg.note in pressed: |
| 61 | + print("noteOff:", msg.note, "vel:", msg.velocity) |
| 62 | + note = pressed[msg.note] |
| 63 | + synth.release(note) |
| 64 | + del pressed[msg.note] |
0 commit comments