## OpenSheetMusicDisplay (OSMD)

This project draws sheet music from MusicXML with OSMD, the npm package `opensheetmusicdisplay`. These notes are written for OSMD 3.0. Every code block below is a file the OSMD website's CI runs against the published package. Source: https://opensheetmusicdisplay.org/agents-snippet.md

Docs: https://opensheetmusicdisplay.org/docs/ (React, Vue, Angular, Svelte, Node.js, cursor, options, transposition). FAQ: https://opensheetmusicdisplay.org/docs/faq/. Every option with its default: `IOSMDOptions` in the API reference, https://opensheetmusicdisplay.github.io/classdoc/.

### Load, then render

```js
import { OpenSheetMusicDisplay } from 'opensheetmusicdisplay';

const osmd = new OpenSheetMusicDisplay('score', {
  autoResize: true,
  backend: 'svg',
});
await osmd.load('my-score.musicxml');
osmd.render();
```

- `load()` is async; call `render()` after it resolves. It takes a URL, a MusicXML string, a `Document` or a `Blob` (`.musicxml`, `.xml`, compressed `.mxl`).
- Files from users are untrusted: `load()` rejects when a file can't be read, and broken MusicXML can still make `render()` throw. Wrap both in one `try`/`catch`.
- A page opened as `file://` can't fetch the score: serve it over HTTP.
- Without a bundler: `build/opensheetmusicdisplay.min.js` from the package defines `window.opensheetmusicdisplay`. Pin the version in a CDN address.

### Components

```jsx
import { useEffect, useRef } from 'react';
import { OpenSheetMusicDisplay } from 'opensheetmusicdisplay';

export function ScoreView({ url }) {
  const container = useRef(null);

  useEffect(() => {
    const osmd = new OpenSheetMusicDisplay(container.current);
    osmd
      .load(url)
      .then(() => osmd.render())
      .catch((error) => {
        // AbortError: url changed, or the component unmounted, before the file arrived
        if (error.name !== 'AbortError') console.error(error);
      });
    return () => osmd.destroy();
  }, [url]);

  return <div ref={container} />;
}
```

- One OSMD instance per container. Call `destroy()` when the component goes away or the score changes (new in 3.0); create a new instance afterwards. Vue, Angular and Svelte follow the same pattern: https://opensheetmusicdisplay.org/docs/vue/, https://opensheetmusicdisplay.org/docs/angular/, https://opensheetmusicdisplay.org/docs/svelte/.
- `destroy()` aborts a `load()` still running, which then rejects with an `AbortError`: let that one pass, as the sample does.
- On 2.x there is no `destroy()`: call `clear()` and `dispose()`, then empty the container.
- Next.js App Router: the component file needs `'use client'`. Importing OSMD on the server is safe; it touches the DOM only when you create an instance.

### Pitfalls

- `Zoom` has a capital Z, and only `render()` applies it: `osmd.Zoom = 0.8; osmd.render();`. OSMD lays the score out again, so a smaller zoom fits more measures per line.
- Options go into the constructor or `setOptions()`; `render()` shows them. A few (`renderSingleHorizontalStaffline`, the default notehead color) work only when set before `load()`.
- Every `render()` replaces the SVG elements, and OSMD also renders by itself (`autoResize`, batches). Re-attach listeners and colors in the `onRender` option (3.0):

```js
import { OpenSheetMusicDisplay } from 'opensheetmusicdisplay';

const osmd = new OpenSheetMusicDisplay('score', {
  // Every render draws new SVG elements: this runs after each one,
  // also after the renders autoResize starts.
  onRender: () => {
    for (const note of document.querySelectorAll('#score .vf-stavenote')) {
      note.addEventListener('click', () => note.classList.toggle('selected'));
    }
  },
});
await osmd.load('my-score.musicxml');
osmd.render();
```

- `autoResize` is on by default. In 3.0 it follows the container's width, and `render()` skips a hidden container (no width). Up to 2.3.1 it followed the window.
- Transposing needs a calculator first; without one, `Transpose` does nothing. No reload needed:

```js
import { IntervalTransposeCalculator } from 'opensheetmusicdisplay';

osmd.TransposeCalculator = new IntervalTransposeCalculator();
osmd.Sheet.Transpose = 3; // semitones: C major becomes E flat major
osmd.render();
```

- Cursor: OSMD counts octaves three lower than scientific pitch, so middle C is octave 1. `Pitch.ToStringShort(3)` gives `C4`:

```js
osmd.cursor.show();
osmd.cursor.next();
const notes = osmd.cursor.NotesUnderCursor();
console.log(notes.map((note) => (note.isRest() ? 'rest' : note.Pitch.ToStringShort(3))));
osmd.cursor.reset();
```

- The option `followCursor` scrolls the page at every cursor step. Leave it off on pages people scroll themselves.
- OSMD is a renderer, not an editor: you can hide, color or skip elements, not move or add notes.
- OSMD brings its own patched VexFlow 1.2.93. Don't install VexFlow 4 or 5 for it.
- Node.js: the package is a CommonJS build, so take the default export (`import osmdModule from 'opensheetmusicdisplay'; const { OpenSheetMusicDisplay } = osmdModule;`). OSMD needs jsdom's `window`, `document`, `DOMParser` and `Node` as globals, a container with an `offsetWidth`, and `autoResize: false`. The full script: https://opensheetmusicdisplay.org/docs/node/.

### Free, and what is OSMD Extended

Public OSMD is BSD-3, free for any use, commercial included: rendering, cursor, options, transposition, Music Braille. OSMD Extended, the build for GitHub Sponsors, adds the audio player (playback, WAV and MP3 export), Jianpu and OSMD Native (React Native, iOS, Android). Public OSMD plays no audio: don't suggest playback APIs unless this project has OSMD Extended. https://opensheetmusicdisplay.org/sponsor/
