Dittytoy
The dittytoy package is a powerful package that allows you to compile and play ditties
from Dittytoy.net.
Dittytoy.net is an online platform that allows you to create generative music using a
minimalistic javascript API using Web Audio.
The API syntax is loosely based on the syntax of Sonic Pi. You can find the
full Dittytoy API Reference here.
Getting started
Installing
Add dittytoy
to your project:
npm i dittytoy
Basic usage
Compile a ditty and play.
import {Dittytoy} from 'dittytoy';
const dittytoy = new Dittytoy();
dittytoy.compile(`
ditty.bpm = 120;
loop( () => {
for (let i=0; i<4; i++) {
sine.play(c4, { attack: 0.01, release: 0.25, duration: 0.125, pan: Math.random() * 2 - 1, amp: 1.0 });
sleep( 0.25 );
}
sine.play(d4, { attack: 0.01, release: 0.25, duration: 0.25 }); // attack and release in seconds, duration in ticks
sleep(0.5); // sleep in ticks
sine.play(f4, { attack: 0.01, release: 0.75, duration: 0.25 });
sleep(0.5);
}, { name: 'my first loop' });
`).then(() => {
dittytoy.play();
})
Note: most browsers only allow audio to be played after a user interaction. You should use the play
method to start the
audio after a user interaction.
Events
Dittytoy emits events that you can listen to by subscribing to the addEventListener
method.
dittytoy.addEventListener(MSG_PLAY, () => {
console.log('Dittytoy starts playing');
});
Some of the events you can listen to are:
Logging
dittytoy.addEventListener(MSG_LOG, (data: any) => {
console.log(data.message);
});
dittytoy.addEventListener(MSG_ERROR, (data: any) => {
console.error(data.message);
});
Initialization
dittytoy.addEventListener(MSG_INIT, (data:any) => {
console.log('Dittytoy is initialized, ready to play');
console.log('Structure of compiled ditty:', data.structure);
});
Playback
dittytoy.addEventListener(MSG_NOTE_PLAYED, (data:any) => {
console.log(`♪ tick: ${data.tick.toFixed(3)}, note: ${data.note} (${data.loop}.${data.synth})`);
});
dittytoy.addEventListener(MSG_UPDATE, (data:any) => {
const state = data.state;
if (state) {
console.log(`tick: ${(state.tick || 0).toFixed(3)}, time: ${(state.time || 0).toFixed(3)} (${state.bpm.toFixed(0)} bpm)`);
}
});
Flow
dittytoy.addEventListener(MSG_PLAY, () => {
console.log('play');
});
dittytoy.addEventListener(MSG_PAUSE, () => {
console.log('pause');
});
dittytoy.addEventListener(MSG_STOP, () => {
console.log('stop');
});
dittytoy.addEventListener(MSG_RESUME, () => {
console.log('resume');
});
Building
To build Dittytoy, ensure that you have Git
and Node.js installed.
Clone a copy of the repo:
git clone https://github.com/reindernijhoff/dittytoy-package.git
Change to the dittytoy directory:
cd dittytoy-package
Install dev dependencies:
npm i
Build package:
npm run build