Audio
hub.audio (hub._audio_module) drives the NS4168 Class-D I2S
amplifier. It provides both raw PCM file playback and a built-in tone
synthesis engine.
Note
hub.audio is only present on boards where hub.board.HAS_NS4168 == 1.
Overview
All playback functions share a single background task. Starting a new
playback stops any ongoing one automatically. Use block=False to return
immediately and poll is_finished() from your script.
Synthesis
The synthesis engine generates PCM in real time at the board’s default sample rate. Two global settings affect all synthesis methods:
Wave type (default "sine"):
hub.audio.set_wave_type("sine") # smooth tone
hub.audio.set_wave_type("square") # buzzy 8-bit feel
hub.audio.set_wave_type("sawtooth") # bright, edgy
Note speed / BPM (default 120):
hub.audio.set_note_speed(90) # slower — 90 beats per minute
Beep
hub.audio.beep(440, 500) # A4 for 500 ms
hub.audio.beep(880, 200, block=False) # non-blocking
Notes
note() accepts a note name string or a MIDI integer.
Duration is in beats at the current BPM.
hub.audio.note("C4", 1) # quarter note C4
hub.audio.note("D#4", 0.5) # eighth note D#4
hub.audio.note("Bb3", 2) # half note Bb3
hub.audio.note("REST", 1) # one beat of silence
hub.audio.note(69, 1) # A4 by MIDI number
Note names follow the format <letter>[#|b]<octave> where letter is
A–G, optional # (sharp) or b (flat), and octave is a single
digit (0–9).
Melody playback
Built-in melodies
hub.audio.play_melody("startup")
hub.audio.play_melody("dadadum") # Beethoven 5th motif
Available names:
Name |
Description |
|---|---|
|
3-note ascending fanfare |
|
3-note descending |
|
Short positive fanfare |
|
Descending minor phrase |
|
Beethoven 5th opening motif |
|
Super Mario Bros opening |
|
Nokia ringtone |
User melodies
Pass a list of (note, length) tuples. Each note is a name string or
MIDI integer; each length is in beats at the current BPM.
hub.audio.set_note_speed(120)
hub.audio.play_melody_from_list([
("C4", 1), ("E4", 1), ("G4", 1), ("C5", 2),
("G4", 1), ("C5", 3),
])
MIDI file playback
play_midi() plays a Standard MIDI File (SMF).
Formats: SMF format 0 (single track) and format 1 (multi-track merged).
Polyphony: up to 8 simultaneous voices; excess voices are stolen.
Tempo: respects Set Tempo meta events in the file.
Wave type: the global wave type applies to all MIDI voices.
hub.audio.set_wave_type("sine")
hub.audio.play_midi("/sd/song.mid")
# Non-blocking — keep doing other work while music plays
hub.audio.play_midi("/sd/bgm.mid", block=False)
while not hub.audio.is_finished():
hub.sleep(100)
File playback
Raw PCM files (no header, signed 16-bit or 8-bit samples):
hub.audio.play("/sd/sound.pcm", rate=44100, bits=16, channels=1)
Stopping playback
hub.audio.stop() # stops any ongoing playback
hub.audio.is_finished() # True when idle