A mini piano component based on the JavaScript Web Audio API, for playing the basic tone of a piano using the Audio Context in a web app.
The Lite-piano is a basic library, you can use it to do your applications logic or any other piano-like music web apps. This is a Demo, which introduces a musicXML score of "Canon D Major" and parses it into lite-piano recognizable parameters. we uses setTimeout to play it automatically. (The demo did not do extra network optimization. It may take about 3.5Mb to load audio and music scores. Please wait patiently and click Play after loading.)
See Readme with 中文版
Download the source code, put /dist/index.js
where you need it, and load the contents of /dist/index.js
directly into the page.
git clone
cd lite-piano
npm install
npm run start
start webpack-dev-server。- Open the browser
127.0.0.1:9090/demo/index.html
You should load index.js into your page. After loading, the constructor will be mounted to the window
global variable. So you can use it as follows:
const LitePiano = window.LitePiano;
const piano = new LitePiano();
piano.resume().then(() => {
piano.initAllSound(); // load all basic on shot sound.
}).then(() => {
document.getElementById('button').addEventListener('click', () => {
piano.oneShot('C', 4, 0); // play a DO pitch.
});
});
This method returns a Promise. On the IOS, the audio contexts are automatically suspended, requiring the user to manually trigger an event to unlock. Therefore, after executing this function, the logic implementation after the user interaction is unlocked can be directly executed.
piano.resume().then(() => {
// you can do something after user interact. and the web audio api is ok.
});
This function returns a Promise. Since the loading and processing of the 7 basic scales is asynchronous, you need to perform this method to ensure that the tones on all pianos are played correctly.
piano.initAllSound().then(() => {
// all sound is inited, now you can play it.
});
This function returns an audio source object, and play a pitch sound. Step indicates the tone name, respectively: C, D, E, F, G, A, B. Octave represents octave, max is 8, and min is 0. eg. The standard piano key C has an octave of 4 And alter = 1 indicates an alter step tone, for example: C#, F#, etc. Usually, The alter tone is the black key on the piano.
piano.oneShot('C', 4, 0);
It is not compatible for IE series, due to using JavaScript Web Audio API to implement. Sorry to see that.
- Chrome: up to 49
- FireFox: up to 61
- Edge: 17
- Safari: 11.1
- iOS Safari: up to 10.3
- Chrome for Android: up to 69