库代码示例

运行一个小型乐谱流程。

区分内存中的库调用、CLI 文件操作和浏览器宿主显示。

在 Rust 中编辑乐谱

ScoreEngine 校验命令并保留撤销历史。

use acorde::core::{Command, ScoreEngine, SetTempoCmd};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut engine = ScoreEngine::new();
    engine.apply(Command::SetTempo(SetTempoCmd { bpm: 144 }))?;
    engine.undo()?;
    println!("{} BPM", engine.score.settings.tempo_bpm);
    Ok(())
}

将 MusicXML 渲染为 SVG

CLI 负责输入和输出文件。将示例保存为 input.musicxml,再在 Acorde 仓库中运行命令。

cargo run -p acorde-cli -- render input.musicxml output.svg

构建 WASM 绑定

从 Acorde v1.3.15 构建,并通过 HTTP 提供仓库根目录。

wasm-pack build crates/wasm --target web
python3 -m http.server 8000

在浏览器渲染

在仓库根目录保存为 preview.html,然后打开 localhost:8000/preview.html。

<!doctype html>
<meta charset="utf-8">
<title>Acorde WASM preview</title>
<img id="score-preview" alt="Rendered MusicXML score">
<script type="module">
  import init, { parse_musicxml_render_svg } from './crates/wasm/pkg/acorde_wasm.js';
  await init();
  const xml = await (await fetch('./tests/fixtures/simple.musicxml')).text();
  const svg = parse_musicxml_render_svg(xml, '{}');
  const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
  const image = document.querySelector('#score-preview');
  image.addEventListener('load', () => URL.revokeObjectURL(url), { once: true });
  image.src = url;
</script>