Building a Piano Ear-Training Application with React and Tone.js
Learning to play an instrument involves more than reading sheet music and memorizing finger positions. Recognizing a note by ear, identifying intervals and associating a sound with the correct piano key can be practiced independently with a small interactive application.
I planned a browser-based piano ear-training project called Piano Jingle as a learning tool for my child. The proposed stack was React, Tone.js, Web MIDI, Web Audio, pitch detection and a Flask backend. This article describes the design and a working-style starting point for the core exercise rather than claiming the complete project has been shipped.
Start with a simple learning loop
The first exercise should be easy to understand: listen to a note, select the matching piano key, and receive immediate feedback. Beginners benefit from a limited range and repeated practice. More advanced exercises can introduce intervals, sequences, chords and a larger keyboard.
The initial application does not need user accounts, machine learning or a complex backend. It needs low-latency audio, a reliable answer mechanism, accessible controls and a clear learning progression.
Choose the browser APIs deliberately
Tone.js provides musical abstractions over the Web Audio API, including synthesizers, note names and scheduling. Web MIDI allows supported browsers to receive messages from a connected MIDI keyboard. A microphone can support acoustic instruments through pitch detection, although browser support and real-world noise make that path more challenging.
| Component | Responsibility |
|---|---|
| React | Exercise state, keyboard, feedback and accessibility |
| Tone.js | Note synthesis and timing |
| Web MIDI | Input from a compatible digital keyboard |
| Web Audio + pitch detection | Optional microphone-based answers |
| Flask | Optional progress API and persistent storage |
Implement the first exercise
Create a small React app and install Tone.js:
npm create vite@latest piano-jingle -- --template react
cd piano-jingle
npm install
npm install tone
npm run dev
Replace src/App.jsx with the following starter component. The first user interaction initializes audio, which browsers commonly require. It uses the answer buttons as a minimal virtual keyboard.
import { useEffect, useRef, useState } from 'react';
import * as Tone from 'tone';
const notes = ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4'];
export default function App() {
const synth = useRef(null);
const [target, setTarget] = useState(null);
const [feedback, setFeedback] = useState('Play a note to begin.');
const [answered, setAnswered] = useState(false);
const [score, setScore] = useState({ correct: 0, total: 0 });
useEffect(() => {
const instrument = new Tone.Synth().toDestination();
synth.current = instrument;
return () => {
instrument.dispose();
synth.current = null;
};
}, []);
async function play(note) {
try {
await Tone.start();
synth.current?.triggerAttackRelease(note, '4n');
} catch {
setFeedback('Audio could not start. Check your browser settings.');
}
}
function next() {
const note = notes[Math.floor(Math.random() * notes.length)];
setTarget(note);
setAnswered(false);
setFeedback('Which note did you hear?');
void play(note);
}
function answer(note) {
if (!target || answered) return;
const correct = note === target;
setScore(s => ({ correct: s.correct + Number(correct), total: s.total + 1 }));
setAnswered(true);
setFeedback(correct ? 'Correct!' : `The answer was ${target}.`);
}
return (
<main>
<h1>Piano Jingle</h1>
<button onClick={next}>New note</button>
<button disabled={!target} onClick={() => play(target)}>Replay</button>
<div aria-label="Choose a note">
{notes.map(note => (
<button key={note} disabled={!target || answered}
onClick={() => answer(note)}>{note}</button>
))}
</div>
<p aria-live="polite">{feedback}</p>
<p>Score: {score.correct} / {score.total}</p>
</main>
);
}
This example is intentionally minimal and has not been tested here in a browser. It is a foundation for adding a styled piano keyboard and exercises, not a full accessibility-tested application.
Extend it to a physical keyboard
In browsers supporting Web MIDI, request MIDI access after a user action and listen for note-on messages. MIDI note 60 corresponds to middle C, commonly labeled C4. Treat note-on messages with zero velocity as note-off. Route accepted events to the same answer logic used by the virtual keyboard, and detach event handlers when the component unmounts. Feature-detect Web MIDI and keep the virtual keyboard available as a fallback.
For microphone input, request explicit permission and use a pitch detector on short audio buffers. Convert a stable estimated frequency to a MIDI note with 69 + 12 × log2(f / 440), then round and apply a confidence/tolerance threshold. Stop audio tracks when the exercise ends. Process microphone input locally when possible; there is no need to upload a child's audio for this exercise.
Design for learning, not just features
Introduce progressively harder exercises, track accuracy by note or interval, and provide specific feedback rather than punishing mistakes. A Flask API can persist aggregate progress later if needed; a local-storage prototype may be enough initially. Protect children's privacy, avoid unnecessary identifiers and provide a way to delete progress data.
The most rewarding aspect of this project is how much can be accomplished with ordinary browser APIs. The right first milestone is not an elaborate music-learning platform. It is a small exercise that makes practicing a musical skill enjoyable, immediate and repeatable.
