A web audio piano instrument
This is a fork of @tonejs/piano by Yotam Mann with performance optimizations and more active maintaince. Built on high-quality samples from Salamander Grand Piano.
- High-quality samples - Up to 16 velocity levels across 88 keys (Yamaha C5)
- Complete instrument - Includes pedal sounds and string harmonics
- Buffer caching - Audio buffers are cached and shared across multiple piano instances
Install the npm package:
npm install --save d-piano
d-piano requires Tone.js as a peer dependency:
npm install --save tone
import { Piano } from 'd-piano'
// create the piano and load 5 velocity steps
const piano = new Piano({
velocities: 5
})
// connect it to the speaker output
piano.toDestination()
// load all samples (returns a promise)
piano.load().then(() => {
console.log('Piano loaded!')
})
The enhanced caching system makes creating multiple pianos efficient:
// Create multiple piano instances - audio buffers are shared automatically
const piano1 = new Piano({ velocities: 3 })
const piano2 = new Piano({ velocities: 5 })
const piano3 = new Piano({ velocities: 1 })
// Load all pianos - samples are fetched only once and shared
Promise.all([
piano1.load(),
piano2.load(),
piano3.load()
]).then(() => {
console.log('All pianos loaded with optimized caching!')
})
interface PianoOptions {
velocities: number; // Number of velocity steps to load (default: 1, max: 16)
minNote: number; // Lowest MIDI note to load (default: 21)
maxNote: number; // Highest MIDI note to load (default: 108)
release: boolean; // Include release sounds (default: false)
pedal: boolean; // Include pedal sounds (default: true)
url: string; // Custom sample URL (optional)
maxPolyphony: number; // Max simultaneous notes (default: 32)
volume: { // Component volume levels in dB (default: 0)
pedal: number;
strings: number;
keybed: number;
harmonics: number;
}
}
Press a note down on the piano.
// Play a 'C4' immediately
piano.keyDown({ note: 'C4' })
// Play a 'C4' 1 second from now with velocity 0.8
piano.keyDown({ note: 'C4', time: '+1', velocity: 0.8 })
Release a note at the given time.
// Release the pressed 'C4' immediately
piano.keyUp({ note: 'C4' })
Press and hold the sustain pedal. Notes played while the pedal is down will be sustained until the pedal is released.
Release the sustain pedal and dampen any sustained notes.
Load all audio samples. Returns a promise that resolves when loading is complete.
Clean up the piano instance and free resources.
npm run build
npm test
npm run lint
This project builds upon the great work of:
- @tonejs/piano by Yotam Mann - The original high-quality piano instrument that serves as the foundation for this project
- Tone.js by Yotam Mann - The Web Audio framework that powers the audio engine
- Salamander Grand Piano - The high-quality piano samples used in this instrument
MIT License - see LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.