PlayScan Developers

Guide

Turn a photo of sheet music into MusicXML and MIDI with Python

You have a photo or a PDF of printed sheet music and you want something your code can work with: notes, rhythms, parts. This guide sends the image to the PlayScan API and gets back MusicXML (which notation software and libraries like music21 read) and MIDI (which anything that plays audio reads).

The whole flow is three HTTP calls: send the page, ask for the status every 2 seconds until it is done, download the result. No SDK is required and there is no webhook to host. If you prefer a client library, pip install playscan and npm install playscan wrap the same three calls.

What works and what doesn't. The API is built for printed music: published editions, engraved scores, clean scans and phone photos of them. It is not built for handwritten scores. Recognition is automatic and can make mistakes, so check the output before you rely on it. You are charged only for pages that were read: a page that fails comes back to your balance.

What you need

  • An API key. Sign up at developer.playscan.app. New accounts get 10 free pages once, no card needed.
  • Python 3.9+ with requests (pip install requests), or Node 18+, or just curl.
  • A photo or scan of a printed page. JPEG, PNG and TIFF images work, or one PDF.

Keep the key out of your code. Every example below reads it from an environment variable:

export PS_KEY=ps_live_...

Call the API from a server or a script, not from a web page: CORS is not enabled, so browsers block the request.

The full Python script

Save this as scan.py and run python scan.py page1.jpg. It writes score.musicxml in the current folder.

import os
import sys
import time

import requests

API = "https://api.playscan.app"
HEADERS = {"Authorization": f"Bearer {os.environ['PS_KEY']}"}


def call(method, path, **kwargs):
    """One API call. Waits and retries when the API says to (429 rate_limited, 503 busy)."""
    while True:
        r = requests.request(method, f"{API}{path}", headers=HEADERS, timeout=120, **kwargs)
        if r.status_code in (429, 503) and "Retry-After" in r.headers:
            time.sleep(int(r.headers["Retry-After"]))
            continue
        if r.status_code >= 400:
            err = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
            sys.exit(f"{r.status_code} {err.get('code')}: {err.get('message', r.text[:200])}")
        return r


def scan(paths, fmt="musicxml"):
    # 1. Send the pages. They are read in the order you send them.
    #    The bytes are read up front so a retried request sends them again.
    files = [("files", (os.path.basename(p), open(p, "rb").read())) for p in paths]
    job = call("POST", "/v1/scans", files=files).json()
    print("scan", job["id"], "pages:", job["pages"])

    # 2. Ask for the status every 2 seconds until it finishes.
    while True:
        s = call("GET", f"/v1/scans/{job['id']}").json()
        if s["status"] not in ("queued", "processing"):
            break
        print(s["status"], f"{s['progress']}%")
        time.sleep(2)

    if s["status"] != "done":
        # failed: error holds the reason, e.g. no_staff_lines. The pages go back to your balance.
        sys.exit(f"scan {s['status']}: {s['error']}")

    # 3. Download the result.
    res = call("GET", f"/v1/scans/{job['id']}/result", params={"format": fmt})
    print("charged pages:", s["chargedPages"], "pages left:", res.headers.get("X-Balance-Pages"))
    return res.content


if __name__ == "__main__":
    fmt = "musicxml"  # or "mxl", "midi", "zip"
    out = "score." + {"musicxml": "musicxml", "mxl": "mxl", "midi": "mid", "zip": "zip"}[fmt]
    with open(out, "wb") as f:
        f.write(scan(sys.argv[1:], fmt))
    print("saved", out)

A typical run looks like this (the time depends on the page and the queue):

scan 0b6f6d2e-... pages: 1
queued 0%
processing 40%
processing 80%
charged pages: 1 pages left: 49
saved score.musicxml

Pick the output format

Change fmt at the bottom of the script; the file name follows it:

format You get
musicxml score.musicxml, the default
mxl compressed MusicXML
midi a standard MIDI file
zip score.musicxml, score.mxl and score.mid in one zip

You can download the same scan in several formats; downloads cost nothing extra. Pages are held from your balance when you send the scan and settled when it finishes: only the pages that were read are charged. Results are kept for 24 hours.

Several pages, or a PDF

Pass several images and they become one score, in that order: python scan.py page1.jpg page2.jpg page3.jpg. Up to 30 pages per scan.

For a PDF, send the file and, if you only want some pages, a pageRange:

import json

files = {"files": ("score.pdf", open("score.pdf", "rb").read())}
data = {"options": json.dumps({"pageRange": [1, 3]})}
job = call("POST", "/v1/scans", files=files, data=data).json()

The same thing in Node

Node 18+ has fetch and FormData built in. Save as scan.mjs and run node scan.mjs page1.jpg.

import { readFile, writeFile } from "node:fs/promises";
import { basename } from "node:path";

const API = "https://api.playscan.app";
const headers = { Authorization: `Bearer ${process.env.PS_KEY}` };
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function call(method, path, body) {
  for (;;) {
    const res = await fetch(`${API}${path}`, { method, headers, body });
    const retry = res.headers.get("retry-after");
    if ((res.status === 429 || res.status === 503) && retry) {
      await sleep(Number(retry) * 1000);
      continue;
    }
    if (!res.ok) {
      const err = await res.json().catch(() => ({}));
      throw new Error(`${res.status} ${err.code}: ${err.message}`);
    }
    return res;
  }
}

// 1. Send the pages.
const form = new FormData();
for (const path of process.argv.slice(2)) {
  form.append("files", new Blob([await readFile(path)]), basename(path));
}
const job = await (await call("POST", "/v1/scans", form)).json();

// 2. Ask for the status every 2 seconds until it finishes.
let s;
do {
  await sleep(2000);
  s = await (await call("GET", `/v1/scans/${job.id}`)).json();
} while (s.status === "queued" || s.status === "processing");
if (s.status !== "done") throw new Error(`scan ${s.status}: ${s.error}`);

// 3. Download the result.
const res = await call("GET", `/v1/scans/${job.id}/result?format=musicxml`);
await writeFile("score.musicxml", Buffer.from(await res.arrayBuffer()));
console.log("saved score.musicxml");

And with curl

Good for trying it once from a terminal:

# 1. Send the page. The answer has the scan id.
curl -s -X POST https://api.playscan.app/v1/scans \
  -H "Authorization: Bearer $PS_KEY" \
  -F "files=@page1.jpg"

# 2. Repeat every 2 seconds until "status" is "done".
curl -s https://api.playscan.app/v1/scans/SCAN_ID \
  -H "Authorization: Bearer $PS_KEY"

# 3. Download the score.
curl -s "https://api.playscan.app/v1/scans/SCAN_ID/result?format=musicxml" \
  -H "Authorization: Bearer $PS_KEY" -o score.musicxml

What to do with the result

  • Analyze it in Python. music21 reads MusicXML: from music21 import converter; score = converter.parse("score.musicxml"). From there you can list notes, transpose, or detect the key.
  • Show it in a browser. OpenSheetMusicDisplay renders MusicXML as notation on a web page.
  • Open it in notation software. MuseScore and most notation programs import MusicXML, so a user can fix mistakes and print.
  • Play it. The MIDI file plays in any MIDI player or DAW, or with a soundfont in the browser.

Getting good results

The photo matters more than anything else:

  • Lay the page flat. Pages that curve toward a book's spine cause many mistakes.
  • Use even light without shadows across the staves.
  • Fit the whole page in the frame and hold the camera straight above it.
  • One page per image. For a book, send each page as its own image, in order.

If a scan comes back failed with no_staff_lines, the API found no music on the page: check that the image really shows a score and is not too dark or blurry.

Limits and errors worth knowing

  • 30 pages per scan; files up to 30 MB each and 60 MB in total.
  • 2 scans queued or processing at a time per account. A third one gets 429 too_many_active; wait for one to finish.
  • Up to 10 new scans a minute and 120 requests a minute in total, per account. Over that you get 429 rate_limited with a Retry-After header, which the scripts above already respect.
  • Sending exactly the same files with the same options again returns the same scan with deduplicated: true and charges nothing, while the earlier scan is still kept: up to 24 hours after it finished, or 1 hour after it failed. A failed scan comes back as failed, so change the image to try again sooner.
  • A scan that is still queued can be canceled with DELETE /v1/scans/{id}; the held pages come back.
  • Not enough pages left gives 402 insufficient_balance. GET /v1/balance shows how many you have.

Every error from the API is JSON with a code and a message. The one exception: a request body over 64 MB is rejected before it reaches the API, with a plain HTTP 413. The full list is in the API docs, along with an OpenAPI file you can import into Postman or generate a client from.

Pricing

After the 10 free pages, you buy pages in packs with a one-time payment, no subscription: from $10 for 100 pages down to $350 for 10,000. Pages never expire. Uploaded images are deleted after 24 hours and are not used to train models. Details are on the pricing page.

Want to see what it produces before writing any code? Try a page in your browser, no account needed.