mcpField
L
lit-sheet-music

lit-sheet-music

github.com/rodydavisクリエイティブ・メディア6065 回インストール2 週間前に更新
リポジトリ

lit-sheet-music について

LitとOpenSheetMusicDisplayでMusicXMLの楽譜を表示するWebコンポーネントを作るスキルです。src属性またはインラインXMLから読み込み、ブラウザー幅に合わせて表示します。

主な機能

  1. 01MusicXMLの楽譜描画
  2. 02src属性またはインラインXML入力
  3. 03SVGまたはcanvasで出力
  4. 04ビューポート変更に応じたリサイズ

活用シーン

  1. 01Webページで楽譜を表示
  2. 02ブラウザー幅に合わせた楽譜描画

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/rodydavis/skills --skill lit-sheet-music

インストール後、Claude Code で/lit-sheet-musicを入力して読み込まれたか確認します。

詳細

Lit Sheet Music

この記事では、Lit ウェブコンポーネントをセットアップし、opensheetmusicdisplay を使って、src 属性またはインライン XML から musicxml をレンダリングする方法を説明します。

README の画像

これで、ブラウザーの幅に合わせて、任意の楽譜を SVG または canvas としてレンダリングできます(ビューポートが変わるとサイズも変更されます)。

TLDR 最終的なソースはこちら、オンラインのデモもあります。

前提条件

  • Vscode
  • Node >= 16
  • Typescript

はじめに

まず、ターミナルでプロジェクトの場所に移動し、次のコマンドを実行します。

npm init @vitejs/app --template lit-ts

次に、プロジェクト名 lit-sheet-music を入力します。続いてプロジェクトを vscode で開き、依存関係をインストールします。

cd lit-sheet-music
npm i lit opensheetmusicdisplay
npm i -D @types/node
code .

vite.config.ts を次の内容で更新します。

import { defineConfig } from "vite";
import { resolve } from "path";

export default defineConfig({
  base: "/lit-sheet-music/",
  build: {
    lib: {
      entry: "src/lit-sheet-music.ts",
      formats: ["es"],
    },
    rollupOptions: {
      input: {
        main: resolve(__dirname, "index.html"),
      },
    },
  },
});

テンプレート

index.html を開き、次の内容で更新します。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Lit Sheet Music</title>
    <script type="module" src="/src/sheet-music.ts"></script>
    <style>
      body {
        margin: 0;
        padding: 0;
      }
    </style>
  </head>

  <body>
    <sheet-music
      src="https://raw.githubusercontent.com/opensheetmusicdisplay/opensheetmusicdisplay/develop/demo/BrahWiMeSample.musicxml"
    >
    </sheet-music>
  </body>
</html>

ローカルの musicxml を使用する場合は、index.html を次の内容で更新します。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Lit Sheet Music</title>
    <script type="module" src="/src/sheet-music.ts"></script>
    <style>
      body {
        margin: 0;
        padding: 0;
      }
    </style>
  </head>

  <body>
    <sheet-music>
      <script type="text/xml">
        <?xml version="1.0" standalone="no"?>
        <!DOCTYPE score-partwise PUBLIC
            "-//Recordare//DTD MusicXML Partwise//EN"
            "http://www.musicxml.org/dtds/partwise.dtd">
          <score-partwise>
            <part-list>
              <score-part id="P1">
                <part-name>Voice</part-name>
              </score-part>
            </part-list>
            <part id="P1">
              <measure number="0" implicit="yes">
                <attributes>
                  <divisions>4</divisions>
                  <key>
                    <fifths>-3</fifths>
                    <mode>major</mode>
                  </key>
                  <time>
                    <beats>2</beats>
                    <beat-type>4</beat-type>
                  </time>
                  <clef>
                    <sign>G</sign>
                    <line>2</line>
                  </clef>
                  <directive>Langsam, innig.</directive>
                </attributes>
                <note>
                  <pitch>
                    <step>G</step>
                    <octave>4</octave>
                  </pitch>
                  <duration>2</duration>
                  <type>eighth</type>
                  <stem>up</stem>
                  <notations>
                    <dynamics>
                      <p/>
                    </dynamics>
                  </notations>
                  <lyric>
                    <syllabic>single</syllabic>
                    <text>W&auml;rst</text>
                  </lyric>
                </note>
              </measure>
              <measure number="1">
                <note>
                  <pitch>
                    <step>F</step>
                    <octave>4</octave>
                  </pitch>
                  <duration>3</duration>
                  <type>eighth</type>
                  <dot/>
                  <stem>up</stem>
                  <lyric>
                    <syllabic>single</syllabic>
                    <text>du</text>
                  </lyric>
                </note>
                <note>
                  <pitch>
                    <step>E</step>
                    <alter>-1</alter>
                    <octave>4</octave>
                  </pitch>
                  <duration>1</duration>
                  <type>16th</type>
                  <stem>up</stem>
                  <lyric>
                    <syllabic>single</syllabic>
                    <text>nicht,</text>
                  </lyric>
                </note>
                <note>
                  <pitch>
                    <step>E</step>
                    <alter>-1</alter>
                    <octave>4</octave>
                  </pitch>
                  <duration>2</duration>
                  <type>eighth</type>
                  <stem>up</stem>
                  <lyric>
                    <syllabic>begin</syllabic>
                    <text>heil</text>
                  </lyric>
                </note>
                <note>
                  <pitch>
                    <step>B</step>
                    <alter>-1</alter>
                    <octave>4</octave>
                  </pitch>
                  <duration>1</duration>
                  <type>16th</type>
                  <stem>up</stem>
                  <beam number="1">begin</beam>
                  <beam number="2">begin</beam>
                  <notations>
                    <slur type="start" number="1"/>
                  </notations>
                  <lyric>
                    <syllabic>end</syllabic>
                    <text>ger</text>
                    <extend/>
                  </lyric>
                </note>
                <note>
                  <pitch>
                    <step>G</step>
                    <octave>4</octave>
                  </pitch>
                  <duration>1</duration>
                  <type>16th</type>
                  <stem>up</stem>
                  <beam number="1">end</beam>
                  <beam number="2">end</beam>
                  <notations>
                    <slur type="stop" number="1"/>
                  </notations>
                  <lyric>
                    <extend/>
                  </lyric>
                </note>
              </measure>
            </part>
          </score-partwise>
      </script>
    </sheet-music>
  </body>
</html>

この例ではウェブコンポーネントに src 属性を渡していますが、内容に json を含む、type 属性を text/xml に設定したスクリプトタグを追加することもできます。

ウェブコンポーネント

コンポーネントを更新する前に、my-element.ts を sheet-music.ts に名前を変更する必要があります。

sheet-music.ts を開き、次の内容で更新します。

import { html, css, LitElement } from "lit";
import { customElement, property, query } from "lit/decorators.js";
import { IOSMDOptions, OpenSheetMusicDisplay } from "opensheetmusicdisplay";

type BackendType = "svg" | "canvas";
type DrawingType = "compact" | "default";

@customElement("sheet-music")
export class SheetMusic extends LitElement {
  _zoom = 1.0;

  @property({ type: Boolean }) allowDrop = false;
  @property() src = "";

  @query("main") canvas!: HTMLElement;

  controller?: OpenSheetMusicDisplay;
  options: IOSMDOptions = {
    autoResize: true,
    backend: "canvas" as BackendType,
    drawingParameters: "default" as DrawingType,
  };

  static styles = css`
    main {
      overflow-x: auto;
    }
  `;

  render() {
    return html`<main></main>`;
  }

  async renderMusic(content: string) {
    if (!this.controller) return;
    await this.controller.load(content);
    this.controller.zoom = this._zoom;
    this.controller.render();
    this.requestUpdate();
  }

  private async getMusic(): Promise<string> {
    // Check if src attribute is set and prefer it over the slot
    if (this.src.length > 0) return fetch(this.src).then((res) => res.text());

    // Check if slot children exist and return the xml
    const elem = this.parentElement?.querySelector(
      'script[type="text/xml"]'
    ) as HTMLScriptElement;
    if (elem) return elem.innerHTML;

    // Return nothing if neither is found
    return "";
  }

  async firstUpdated() {
    this.controller = new OpenSheetMusicDisplay(this.canvas, this.options);
    this.requestUpdate();

    // Check for any music and update if found
    const music = await this.getMusic();
    if (music.length > 0) this.renderMusic(music);
  }
}

declare global {
  interface HTMLElementTagNameMap {
    "sheet-music": SheetMusic;
  }
}

npm run dev を実行します。すべて正常に動作すれば、次のように表示されます。

README の画像

まとめ

Lit を使った開発について詳しく知りたい場合は、ドキュメントをこちらでご覧ください。

この例のソースはこちらにあります。

README の画像

コメント