Skip to content

Getting started ​

Install ​

bash
npm install plonkjs

Write a song ​

A song is an object: a tempo, some instruments, and sections of patterns played in order.

ts
import type { Song } from "plonkjs";

export const theme: Song = {
  bpm: 112,
  swing: 0.12,
  instruments: {
    lead: { wave: "square", decay: 0.14, sustain: 0.35, volume: 0.15, echo: 0.3 },
    bass: { wave: "sawtooth", octave: -1, volume: 0.22, filter: { cutoff: 380, q: 9, sweep: 1400 } },
    kick: { wave: "sine", drop: 24, decay: 0.12, sustain: 0, volume: 0.5 },
    hat: { wave: "noise", decay: 0.03, sustain: 0, volume: 0.08, filter: { cutoff: 9000 } },
  },
  sections: {
    a: {
      lead: "C5 . E5 G5 . E5 C5 . | D5 . F5 A5 . F5 D5 .",
      bass: "C3 . . C3 . . G2 . | D3 . . D3 . . A2 .",
      kick: "x . . . x . . .",
      hat: ". . x . . . x .",
    },
  },
  order: ["a", "a"],
};

Each step is a sixteenth note. Songs and patterns covers the whole notation, and Instruments every sound setting.

Play it ​

ts
import { Player } from "plonkjs";
import { theme } from "./theme";

const player = new Player();
player.play(theme, { fade: 1 }); // fade in over a second; it loops until you stop it

Browsers only start audio after the player clicks, taps or presses a key. Start the music from a click, or create the player early: it begins as soon as the browser allows sound.

Stop, or change the mood ​

ts
player.tempo(1.15); // 15% faster, without a jump
player.layer("kick", 0); // fade the kick out
player.stop(1); // fade everything out over a second

Music that reacts shows how to tie these to your game. With a game engine, pass its audio context so the music shares its volume and mute: see With a game engine.