piezotone

package module
v0.0.0-...-f189cb4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

piezotone

piezotone turns MIDI and audio files into melodies for piezo buzzers. It is a Go library and a command. It has no cgo, so it builds for any Go target with CGO_ENABLED=0.

piezotone song.mid                       # OpenDisplay melody notation
piezotone -format rtttl whistle.wav      # Nokia RTTTL ringtone
piezotone -format midi -o one-voice.mid song.mid
opendisplay buzz -melody "$(piezotone song.mid)"

What it does

  1. It reads the file and finds one voice:
    • MIDI: it plays the track and channel with the most notes. It skips the drums on channel 9 (10 in General MIDI numbering). When notes overlap, the highest note sounds.
    • Audio: every 10 ms it sums the spectrum at the partials of each semitone (harmonic summation) and follows the loudest voice with a smooth path (Viterbi). This keeps the melody over a quieter backing chord or bass. Then it cuts the pitch track into notes:
      • a note starts at its attack, also when a singer slides up into it;
      • a repeated note starts again (the energy at its partials rises again);
      • a partial taken as a note (an octave or a twelfth too high) gets the right pitch.
    • Drums (-drums, audio only): a harmonic/percussive split finds the drum hits. A hit strikes a held note again, and a hit in a rest becomes a short high tick.
  2. It gives note events: piezotone.Note{MIDI, Start, Duration}. MIDI is a MIDI note number (69 is A4, 440 Hz) or piezotone.Rest.
  3. An output profile writes the notes for a device or a format.

What it cannot do

  • One voice only. A piezo buzzer plays one square-wave tone at a time. In MIDI, chords become their highest note. In audio, piezotone follows the loudest voice. Full songs in which no one voice is clearly the loudest give poor results.
  • No speech, noise or drums as a melody. These sounds have no stable pitch (-drums uses drum hits for rhythm only). piezotone then stops with a "found no notes" message. The message gives the length, the loudness, the share of voiced frames and the best pitch contrast: how many times stronger the best pitch is than the mean pitch. A clear tone gives 5 or more; white noise stays below 3. For a rough pitch, try -voicing 2.5 to 2.
  • No timbre. A piezo plays square-wave tones only. The output keeps pitch and rhythm only.

Formats

-format Package Output
opendisplay (default) opendisplay The melody notation of opendisplay buzz -melody from go-opendisplay, for example A4:200 R:50 G4+:5. It fits the notes to the buzzer: 400 to 12000 Hz, 5 ms steps, at most 1275 ms per note. opendisplay buzz plays a long melody as several frames; -max-notes cuts it for an older CLI that sends one frame.
rtttl rtttl A Nokia RTTTL ringtone, for example song:d=8,o=5,b=112:a,4c6. Octaves 4 to 7. It picks the tempo that fits the note lengths best. Spec: mobilefish.com RTTTL specification.
midi midi A standard MIDI file (type 0) with one voice.

How good is it

A benchmark renders 7 public-domain tunes from MIDI (melody, harmony, pad, bass, drums) and scores the notes against the MIDI melody with mir_eval (onset within 50 ms, pitch within 50 cents).

Mix Note F-measure Pitch correct (frames)
Lead clearly on top 0.75 81%
Lead as loud as the backing 0.38 41%

In a blind listening test of a phone ringtone (sung lead, harmony, sparse drums), the listener rated the output 76 of 100 without -drums and 89 with it. For a song with a steady hi-hat, the listener preferred the output without -drums (86 against 32).

OpenDisplay notes

  • The melody has no volume. The buzzer volume is the duty cycle in the device config (duty_percent; 50% is the loudest). Set it with opendisplay volume -set PERCENT.
  • Tested on one OpenDisplay e-paper display (800 x 480, black and white, firmware 2.27.1) with go-opendisplay, at duty 10%.
  • Pitch, measured with a microphone on that display at duty 30%: all 59 semitones from G#4 (415 Hz) to F#9 (11.8 kHz) play within 1.2 cents of equal temperament (mean 0.4 cents). Note starts are within 10 ms of the plan, also across frames.

Decoders

piezotone finds the input format from the first bytes of the file, not from the file name.

Input Decoder License
MIDI (SMF type 0 and 1) gitlab.com/gomidi/midi/v2 MIT
WAV (integer PCM 8 to 32 bit, float 32 and 64 bit) own reader, standard library only this repository
MP3 (MPEG-1/2 Layer III) github.com/tphakala/go-mp3 MIT
FLAC github.com/mewkiz/flac Unlicense
Ogg Vorbis github.com/jfreymuth/oggvorbis MIT

THIRD_PARTY_NOTICES.md lists all linked modules.

Install

go install github.com/cr2007/piezotone/cmd/piezotone@latest

Command flags

Flag Default Use
-format opendisplay opendisplay, rtttl or midi
-o FILE stdout write the output to FILE
-track N, -channel N -1 (pick) MIDI: the track and channel to play
-voicing V 3 audio: the pitch contrast a frame needs; a lower value finds more notes
-min-note MS 60 audio: the shortest note
-drums off audio: strike held notes again on drum hits and tick on hits in rests; good for sparse drums, too busy for a steady hi-hat
-max-notes N 0 (keep all) opendisplay: cut at N notes and 30 s, for an opendisplay CLI that sends one frame (104 encrypted, 119 plain)
-name NAME file name rtttl: the tune name, at most 10 characters

Warnings, for example "moved the melody up by 2 octave(s)", go to stderr.

Library

data, _ := os.ReadFile("whistle.flac")
samples, rate, err := piezotone.Decode(data)
notes, err := piezotone.FromPCM(samples, rate, piezotone.PCMOptions{})
var nn *piezotone.NoNotesError
if errors.As(err, &nn) {
	// nn.Seconds, nn.RMSDB, nn.Voiced, nn.BestContrast tell why
}
tune, warnings := rtttl.Encode(notes, rtttl.Options{Name: "whistle"})

Use piezotone.FromMIDI for MIDI files and piezotone.IsMIDI to tell the two apart.

Tests

go test ./...

The audio tests synthesize a reference melody (sine and square waves, 44.1 and 48 kHz, WAV and MP3) and want a note F-measure of 1.0. With ffmpeg installed, they also check FLAC, Ogg Vorbis and LAME MP3 files.

Agent skill

skills/piezotone/SKILL.md teaches a coding agent (for example Claude Code) how to use piezotone: which output format to pick, which inputs work, and how to read the "found no notes" message. Install it for Claude Code by copying the folder into your skills directory:

mkdir -p ~/.claude/skills && cp -r skills/piezotone ~/.claude/skills/

License

MIT. See LICENSE.

Documentation

Overview

Package piezotone turns MIDI and one-voice audio into note events for a piezo buzzer. The core knows no device. The packages rtttl, midi and opendisplay write the notes in an output format.

Index

Constants

View Source
const Rest = -1

Rest is the MIDI value of a note that plays no tone.

View Source
const TickMIDI = 96

TickMIDI is the pitch of a drum tick in a rest (C7).

Variables

This section is empty.

Functions

func Decode

func Decode(b []byte) ([]float32, int, error)

Decode reads a WAV, MP3, FLAC or Ogg Vorbis file. It finds the format from the first bytes, mixes the channels down to mono and returns the samples and the sample rate. Integer PCM is in [-1, 1]; float WAV and lossy data can go past it.

func HzMIDI

func HzMIDI(hz float64) int

HzMIDI is the nearest MIDI note number to hz.

func IsMIDI

func IsMIDI(b []byte) bool

IsMIDI reports whether b starts like a standard MIDI file.

func MIDIHz

func MIDIHz(m int) float64

MIDIHz is the frequency of a MIDI note number in equal temperament.

func ReadWAV

func ReadWAV(r io.Reader) ([]float32, int, error)

ReadWAV reads a RIFF WAVE file with integer PCM (8, 16, 24 or 32 bit) or float samples (32 or 64 bit), in any channel count. It mixes the channels down to mono and returns the samples and the sample rate. Integer PCM is in [-1, 1]; float samples are as in the file.

Types

type MIDIOptions

type MIDIOptions struct {
	Track   int // 0 is the first track
	Channel int // 0 to 15
}

MIDIOptions picks the notes to play. A value of -1 means "any". When both are -1, FromMIDI picks the track and channel pair with the most notes.

type NoNotesError

type NoNotesError struct {
	Seconds       float64 // length of the audio
	PeakDB, RMSDB float64 // loudness in dBFS
	Frames        int     // 10 ms analysis frames
	Voiced        int     // frames with a pitch
	BestContrast  float64 // highest ratio of best pitch to mean pitch of all frames that are not silent; 0 if all are silent
	Voicing       float64 // voicing threshold in use
}

NoNotesError tells why FromPCM found no note.

func (*NoNotesError) Error

func (e *NoNotesError) Error() string

type Note

type Note struct {
	MIDI     int
	Start    time.Duration
	Duration time.Duration
}

Note is one step of a melody: a MIDI note number (69 is A4, 440 Hz) or Rest, its start time and its duration. A melody has no gaps: each note starts where the note before it ends.

func FromMIDI

func FromMIDI(r io.Reader, o MIDIOptions) ([]Note, error)

FromMIDI reads a standard MIDI file and returns one voice: when notes overlap, the highest note sounds.

func FromPCM

func FromPCM(samples []float32, rate int, o PCMOptions) ([]Note, error)

FromPCM finds the main melody of mono samples and cuts it into notes. For each 10 ms frame it sums the spectrum at the first partials of every semitone (harmonic summation, Klapuri, ISMIR 2006), then picks the smoothest strong path through the frames (Viterbi). This keeps the melody over a quieter backing chord or bass. It does not work for music in which no one voice is clearly the loudest. When it finds no pitched note, the error is a *NoNotesError. A sample that is NaN or infinite counts as 0.

type PCMOptions

type PCMOptions struct {
	MinHz, MaxHz float64 // pitch search range [80, 5000]
	Voicing      float64 // a frame whose best pitch is less than this many times the mean is unvoiced [3]
	SilenceDB    float64 // a frame this far below the loudest frame is silent [-30]
	MinNoteMS    int     // shorter segments join the segment before them [60]
	Drums        bool    // strike held notes again on drum hits and put a tick on hits in rests
}

PCMOptions tunes FromPCM. Zero values use the defaults in brackets.

Directories

Path Synopsis
cmd
piezotone command
Command piezotone turns a MIDI or audio file into a one-voice melody for a piezo buzzer.
Command piezotone turns a MIDI or audio file into a one-voice melody for a piezo buzzer.
Package midi writes notes as a monophonic standard MIDI file (SMF type 0).
Package midi writes notes as a monophonic standard MIDI file (SMF type 0).
Package opendisplay fits notes to the buzzer of an OpenDisplay device and writes the melody notation that "opendisplay buzz -melody" of github.com/cr2007/go-opendisplay accepts.
Package opendisplay fits notes to the buzzer of an OpenDisplay device and writes the melody notation that "opendisplay buzz -melody" of github.com/cr2007/go-opendisplay accepts.
Package rtttl writes notes in the Nokia RTTTL (Ring Tone Text Transfer Language) format, for example "JingleBell:d=8,o=5,b=112:32p,a,a,4a".
Package rtttl writes notes in the Nokia RTTTL (Ring Tone Text Transfer Language) format, for example "JingleBell:d=8,o=5,b=112:32p,a,a,4a".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址