Run locally
This page takes the score from Write a score off the website. You compile it with the command-line tool, then play it from a small browser application with Play, Stop, and a button that changes the music while it plays.
You need Node.js 22.12 or newer and a browser with Web Audio. To play audio, you also need a Gemini API key from a project with access to Lyria RealTime. The site’s shared audio only works in its own demos.
Compile a score
Save the score as song.gas, then run:
npx @luna-estelar/gas@0.4.0 compile song.gas --out song.timeline.jsonThis writes the timeline as JSON: the score’s events placed in bars, with nothing specific to a model. Timeline format describes its structure. Compiling needs no key and, once the package is downloaded, no network. Leave out --out song.timeline.json to print the JSON instead. If the score has errors, the command prints them and exits with status 1; the language reference explains each kind.
Build the application
Create a TypeScript project with Vite and install GAS:
npm create vite@latest gas-piano -- --template vanilla-ts
cd gas-piano
npm install
npm install --save-exact @luna-estelar/gas@0.4.0 @luna-estelar/gas-lyria-rt@0.4.0@luna-estelar/gas has the language, the session, and browser playback, and @luna-estelar/gas-lyria-rt is the connector for Lyria RealTime. The application imports browser playback from @luna-estelar/gas/browser. Packages and imports lists them all.
Replace index.html with:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GAS piano</title>
</head>
<body>
<label>Gemini API key <input id="key" type="password" autocomplete="off" /></label>
<button id="play">Play</button>
<button id="stop" disabled>Stop</button>
<button id="change" disabled>Make it busier</button>
<p id="status" role="status">Stopped</p>
<p id="warnings"></p>
<script type="module" src="/src/main.ts"></script>
</body>
</html>Replace src/main.ts with the module below. It plays the same score, set to loop so the music keeps going while you change it.
import { GasOperationError, sourceText } from '@luna-estelar/gas';
import { createBrowserSession, type BrowserSession } from '@luna-estelar/gas/browser';
import { createLyriaRtConnector } from '@luna-estelar/gas-lyria-rt';
const score = `
tempo 88
key "C major"
time_signature 4/4
length bars 12 loop
track piano "Soft felt piano"
track bass "Round upright bass, short notes"
section intro:
length bars 4
flavor "quiet, plenty of space"
bar 1:
piano.play
section main:
length bars 4
flavor "warmer, more movement"
bar 1:
bass.play
section outro:
length bars 4
bass.stop
bar 3:
piano.stop
intro()
main()
outro()
`;
const key = document.querySelector<HTMLInputElement>('#key')!;
const play = document.querySelector<HTMLButtonElement>('#play')!;
const stop = document.querySelector<HTMLButtonElement>('#stop')!;
const change = document.querySelector<HTMLButtonElement>('#change')!;
const status = document.querySelector<HTMLParagraphElement>('#status')!;
const warnings = document.querySelector<HTMLParagraphElement>('#warnings')!;
let opening: Promise<BrowserSession> | undefined;
function message(error: unknown): string {
if (error instanceof GasOperationError) {
return `Could not continue: ${error.kind}${error.reason ? ` (${error.reason})` : ''}.`;
}
return 'Could not continue. Check the console and your provider access.';
}
// Creates the session on the first Play and loads the score. Later clicks reuse it.
function open(): Promise<BrowserSession> {
if (opening) return opening;
const current = createBrowserSession({
// Called on every Play, so a corrected key is used next time.
connector: createLyriaRtConnector({ apiKey: () => key.value.trim() })
}).then(async (browser) => {
const { session } = browser;
session.on('state', (state) => {
const busy = state.status === 'starting' || state.status === 'playing';
play.disabled = busy;
stop.disabled = !busy;
change.disabled = state.status !== 'playing';
if (state.ended === 'stopped') status.textContent = 'Stopped';
});
session.on('error', (error) => {
status.textContent = message(error);
});
session.on('warning', (warning) => {
warnings.textContent = warning.message;
});
browser.audio.on('status', (audio) => {
if (session.getState().status === 'playing') status.textContent = `Audio: ${audio.state}`;
});
try {
const loaded = await session.loadSource(sourceText(score));
warnings.textContent = loaded.warnings.map((warning) => warning.message).join(' ');
} catch (error) {
await browser.close();
throw error;
}
return browser;
});
opening = current;
// If it fails, the next click starts again.
current.catch(() => {
if (opening === current) opening = undefined;
});
return current;
}
play.addEventListener('click', async () => {
if (!key.value.trim()) {
status.textContent = 'Enter a Gemini API key first.';
return;
}
play.disabled = true;
status.textContent = 'Connecting…';
// Start before any await, so Web Audio opens inside this click.
const starting = open();
try {
const { session } = await starting;
await session.play();
status.textContent = 'Waiting for audio…';
} catch (error) {
play.disabled = false;
// Stop during start-up cancels Play. That isn't a failure.
if (!(error instanceof GasOperationError && error.kind === 'cancelled')) {
status.textContent = message(error);
}
}
});
stop.addEventListener('click', () => {
void opening?.then((browser) => browser.session.stop());
});
change.addEventListener('click', async () => {
const browser = await opening;
if (!browser) return;
change.disabled = true;
try {
await browser.session.submitLiveCommands(
sourceText('piano.flavor "busier, left hand walking"\ntempo 96')
);
status.textContent = 'Change accepted; listen as the music responds.';
} catch (error) {
status.textContent = message(error);
} finally {
change.disabled = browser.session.getState().status !== 'playing';
}
});
window.addEventListener('pagehide', () => {
void opening?.then(
(browser) => browser.close(),
() => undefined
);
opening = undefined;
});Start the development server, open the local URL that Vite prints, enter your key, and press Play:
npm run devThe status shows Audio: playing once sound reaches your speakers. play() resolves once the connection to Lyria is open, and Lyria takes a few more seconds to send its first audio. Any support warnings for the score appear below the status; Supported models explains them.
Press Make it busier to send a live command to the running session, as you did in the playground. The change lasts until it is cleared, so it is still there after Stop and the next Play.
What the code does
- Starts audio inside the click.
createBrowserSessionis called before the Play handler awaits anything, because some browsers only let audio start inside a user gesture. - Keeps one session. The first Play creates the session and loads the score. Stop calls
session.stop(), and Play callsplay()again on the same session. Each Play opens a new connection to Lyria, so pressing Play after a failure tries again. - Reads the key on every Play.
apiKeyis a function, so a corrected key is used on the next Play without a new session. - Closes on
pagehide. Leaving the page closes the session and its audio context, including one that finishes starting after you leave. The JavaScript API covers Play, Stop, and Close.
The key stays in the page and is never stored. Don’t ship a provider key in your JavaScript: a production application should send requests through its own backend relay. Troubleshooting covers rejected keys, silence, and dropped connections.
Next: Connect with an application — make the music respond to your application’s state.