### Complete Embed Configuration Example Source: https://github.com/flatio/embed-client/blob/master/_autodocs/configuration.md A comprehensive example demonstrating initialization of the Flat Embed Client with various configuration options, including sizing, score loading, lazy loading, and advanced embed parameters. ```typescript import Embed from 'flat-embed'; const embed = new Embed('embed-container', { // Container sizing width: '100%', height: '600px', // Score to load score: '56ae21579a127715a02901a6', // Lazy loading lazy: true, // Advanced configuration embedParams: { // Identification appId: 'your-app-id', userId: 'user-12345', // Display locale: 'en', layout: 'responsive', zoom: 1.0, // Features mode: 'view', controlsPlay: true, controlsFullscreen: true, controlsZoom: true, controlsPrint: true, // Audio playbackMetronome: 'count-in', playbackVolumeMaster: 0.8, // Theme themePrimary: '#1E88E5', branding: true } }); // Ready to use await embed.ready(); await embed.play(); ``` -------------------------------- ### Minimal Embed Player Setup Source: https://github.com/flatio/embed-client/blob/master/_autodocs/INDEX.md This snippet demonstrates the basic setup for embedding a score and initiating playback. Ensure you have the 'flat-embed' package installed and replace 'container', 'score-id', and 'app-id' with your specific values. ```typescript import Embed from 'flat-embed'; const embed = new Embed('container', { score: 'score-id', embedParams: { appId: 'app-id' } }); await embed.play(); ``` -------------------------------- ### Install flat-embed using npm, pnpm, or yarn Source: https://github.com/flatio/embed-client/blob/master/README.md Install the ES/TypeScript Embed Client using your preferred package manager. ```bash npm install flat-embed pnpm add flat-embed yarn add flat-embed ``` -------------------------------- ### TypeScript Setup and Type Usage Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Shows how to import the Embed class and relevant types from 'flat-embed' for full TypeScript support and compile-time error checking. ```typescript import Embed from 'flat-embed'; import type { NoteCursorPosition, PartConfiguration } from 'flat-embed'; const embed = new Embed('container', { score: 'score-id', embedParams: { appId: 'app-id' } }); const pos: NoteCursorPosition = await embed.getCursorPosition(); const parts: PartConfiguration[] = await embed.getParts(); // Type safety ensures compile-time error checking ``` -------------------------------- ### Editor Mode Initialization Source: https://github.com/flatio/embed-client/blob/master/README.md Example of how to initialize the embed in editor mode by setting the `mode` option within `embedParams`. ```APIDOC ## Editor API You can enable the editor mode by setting the `mode` to `edit` when creating the embed: ```js var embed = new Flat.Embed(container, { embedParams: { appId: '', mode: 'edit', }, }); ``` ``` -------------------------------- ### JavaScript API - Quick Examples Source: https://github.com/flatio/embed-client/blob/master/README.md Commonly used methods for interacting with the embed, such as waiting for readiness, loading scores, controlling playback, and listening to events. ```APIDOC ## JavaScript API - Quick Examples ```js // Wait for the embed to be ready await embed.ready(); // Load a score await embed.loadFlatScore('SCORE_ID'); // Control playback await embed.play(); await embed.pause(); await embed.stop(); // Listen to events embed.on('play', () => { console.log('Playback started'); }); embed.on('cursorPosition', position => { console.log('Cursor moved:', position); }); ``` ``` -------------------------------- ### Get Embed Configuration Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Fetches the complete embed configuration, including display settings and permissions. ```typescript const config = await embed.getEmbedConfig(); console.log(`Mode: ${config.mode}`); console.log(`Controls enabled: ${config.controlsPlay}`); ``` -------------------------------- ### TypeScript Usage Example Source: https://github.com/flatio/embed-client/blob/master/README.md Demonstrates how to import and use the Flat Embed SDK with TypeScript, including type checking and autocompletion for methods and events. ```APIDOC ## TypeScript Support This SDK includes TypeScript definitions out of the box. All methods and events are fully typed for better development experience. ```typescript import Embed from 'flat-embed'; const embed = new Embed(container, { score: 'SCORE_ID', embedParams: { appId: 'YOUR_APP_ID', mode: 'view', // TypeScript knows valid modes }, }); // Full type checking and autocompletion const parts = await embed.getParts(); ``` ``` -------------------------------- ### Start Score Playback Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Starts score playback from the current cursor position or resumes from a pause point. Use this to initiate or resume music playback. ```typescript await embed.play(); embed.on('play', () => console.log('Playback started')); ``` -------------------------------- ### Initialize Embed with TypeScript and Type Checking Source: https://github.com/flatio/embed-client/blob/master/README.md This example demonstrates initializing the Flat Embed client using TypeScript, leveraging the provided type definitions for enhanced development experience. It shows how to specify score and embed parameters with type safety. ```typescript import Embed from 'flat-embed'; const embed = new Embed(container, { score: 'SCORE_ID', embedParams: { appId: 'YOUR_APP_ID', mode: 'view', // TypeScript knows valid modes }, }); // Full type checking and autocompletion const parts = await embed.getParts(); ``` -------------------------------- ### Load and Play a Score Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Initializes the embed client and starts playback of a specified score. It also demonstrates how to listen for the 'play' event. ```typescript const embed = new Embed('container', { score: 'score-id', embedParams: { appId: 'app-id' } }); await embed.play(); embed.on('play', () => console.log('Playing')); ``` -------------------------------- ### play() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Starts score playback from the current cursor position. If the score was paused, this method resumes playback from where it left off. ```APIDOC ## play() ### Description Starts score playback from the current cursor position. Resumes from pause point if previously paused. ### Method `play()` ### Returns `Promise` when playback started ### Throws `Error` if no score loaded ### Example ```typescript await embed.play(); embed.on('play', () => console.log('Playback started')); ``` ``` -------------------------------- ### Listen to Embed Events Source: https://github.com/flatio/embed-client/blob/master/README.md This snippet shows how to subscribe to specific events emitted by the embed, such as playback start and cursor position changes. Use this to react to user interactions or playback status. ```javascript // Listen to events embed.on('play', () => { console.log('Playback started'); }); embed.on('cursorPosition', position => { console.log('Cursor moved:', position); }); ``` -------------------------------- ### Get Part UUIDs Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves an array of unique identifiers for all parts in the score. Useful for referencing specific parts, for example, for muting. ```typescript const uuids = await embed.getPartsUuids(); await embed.mutePart({ partUuid: uuids[0] }); ``` -------------------------------- ### Get Measure Voices UUIDs Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Gets voice identifiers for a specific measure and part. Requires the UUIDs of both the part and the measure. ```typescript const parts = await embed.getParts(); const measures = await embed.getMeasuresUuids(); const voices = await embed.getMeasureVoicesUuids({ partUuid: parts[0].uuid, measureUuid: measures[0] }); console.log(`Found ${voices.length} voices`); ``` -------------------------------- ### Initialize Embed Client with Full Configuration Source: https://github.com/flatio/embed-client/blob/master/_autodocs/INDEX.md Initialize the embed client with a comprehensive set of configuration options. Ensure the embed is ready before interacting with it and subscribe to events for real-time updates. ```typescript // Initialize with full configuration const embed = new Embed('container', { score: 'score-id', width: '100%', height: '600px', embedParams: { appId: 'app-id', userId: 'user-123', mode: 'view', locale: 'en', layout: 'responsive', controlsPlay: true, controlsZoom: true } }); // Wait for ready await embed.ready(); // Subscribe to events embed.on('play', () => console.log('Playing')); embed.on('cursorPosition', (pos) => updateUI(pos)); // Control playback await embed.setPlaybackSpeed(0.75); await embed.play(); // Export when done const pdf = await embed.getPDF(); ``` -------------------------------- ### Initialize Embed Client and Event Listeners Source: https://github.com/flatio/embed-client/blob/master/test/manual/test-embedSize.html Sets up the Flat.io Embed client, registers listeners for 'ready', 'scoreLoaded', and 'embedSize' events, and logs messages to the console. Use this to observe embed lifecycle and size changes. ```javascript import Embed from '../../dist/flat-embed.mjs'; const log = document.getElementById('log'); const sizeInfo = document.getElementById('size-info'); const modeInfo = document.getElementById('mode-info'); const container = document.getElementById('embed-container'); // Get params from URL const urlParams = new URLSearchParams(window.location.search); const layout = urlParams.get('layout') || 'responsive'; // Update mode info modeInfo.textContent = `Layout: ${layout}`; // Highlight active buttons document.getElementById(`btn-${layout}`)?.classList.add('active'); function addLog(message) { const time = new Date().toLocaleTimeString(); log.textContent += `[${time}] ${message}\n`; log.scrollTop = log.scrollHeight; } window.clearLog = function() { log.textContent = ''; }; window.resizeContainer = function(width) { const widthStr = typeof width === 'number' ? `${width}px` : width; container.style.width = widthStr; addLog(`Container width set to ${widthStr}`); }; window.switchMode = function(newLayout) { const params = new URLSearchParams(window.location.search); params.set('layout', newLayout); window.location.search = params.toString(); }; addLog(`Creating embed with layout=${layout}... `); const embedParams = { appId: '58f0ee6053674e68c81e5646', controlsFloating: false, layout: layout, }; const embed = new Embed('embed-container', { score: '56ae21579a127715a02901a6', // score: '655421147ae4155c831a5dbe', // baseUrl: 'https://flat.ovh:3000/embed', embedParams: embedParams }); // Listen for ready embed.ready().then(() => { addLog('Embed ready!'); }); // Listen for scoreLoaded embed.on('scoreLoaded', () => { addLog('scoreLoaded event received'); }); // Listen for embedSize and auto-resize iframe height embed.on('embedSize', (data) => { addLog(`embedSize: ${data.width}px × ${data.height}px`); // Set iframe height to match content - no scrollbars! embed.element.style.height = `${data.height}px`; sizeInfo.textContent = `Iframe size: ${data.width}px × ${data.height}px (auto-adjusted)`; }); addLog('Event listeners registered, waiting for events...'); ``` -------------------------------- ### getNbParts() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Gets the total number of instrument parts available in the score. ```APIDOC ## getNbParts() ### Description Gets the total number of parts in the score. ### Method `async` ### Endpoint `embed.getNbParts() ### Parameters None ### Response #### Success Response - `Promise`: The total count of parts in the score. ### Request Example ```typescript const count = await embed.getNbParts(); console.log(`Score has ${count} instruments`); ``` ``` -------------------------------- ### getPartReverb() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Gets the reverb level for a specified part. Requires the UUID of the part. ```APIDOC ## getPartReverb() ### Description Gets the reverb level for a part. ### Method `getPartReverb` ### Parameters #### Path Parameters - **parameters.partUuid** (string) - Required - UUID of the part. ### Response #### Success Response - Returns `Promise`: The reverb level for the part (ranging from 0 to 100). ### Request Example ```typescript const parts = await embed.getParts(); const reverb = await embed.getPartReverb({ partUuid: parts[0].uuid }); ``` ``` -------------------------------- ### getPlaybackSpeed() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Gets the current playback speed multiplier. The speed is a multiplier where 1.0 represents normal speed. ```APIDOC ## getPlaybackSpeed() ### Description Gets the current playback speed multiplier. ### Method `getPlaybackSpeed` ### Response #### Success Response - Returns `Promise`: The playback speed multiplier (ranging from 0.2 to 2.0). ### Request Example ```typescript const speed = await embed.getPlaybackSpeed(); console.log(`Playing at ${speed * 100}% speed`); ``` ``` -------------------------------- ### Embed Constructor with Basic Options Source: https://github.com/flatio/embed-client/blob/master/_autodocs/configuration.md Instantiate the Embed SDK with basic configuration options. All options are optional and use sensible defaults. ```typescript const embed = new Embed(element, { score?: string; width?: string; height?: string; baseUrl?: string; isCustomUrl?: string; lazy?: boolean; embedParams?: { // Detailed options below } }); ``` -------------------------------- ### ready() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Waits for the embed to be ready. The embed automatically calls this internally before other methods, so explicit calls are optional. Resolves when the embed is ready for interactions. ```APIDOC ## ready() ### Description Waits for the embed to be ready. The embed automatically calls this internally before other methods, so explicit calls are optional. Resolves when the embed is ready for interactions. ### Returns - **Promise** - that resolves when the embed is ready ### Request Example ```typescript const embed = new Embed('container', { score: 'score-id' }); await embed.ready(); console.log('Embed is ready for interactions'); ``` ``` -------------------------------- ### Get and Reference Parts Source: https://github.com/flatio/embed-client/blob/master/_autodocs/quick-reference.md Retrieve all parts of a score and reference them by their UUID for precise control, or by array index. ```typescript // Get all parts const parts = await embed.getParts(); // Reference by UUID (recommended) const uuid = parts[0].uuid; await embed.setPartVolume({ partUuid: uuid, volume: 75 }); // Reference by array index const uuids = await embed.getPartsUuids(); await embed.mutePart({ partUuid: uuids[0] }); ``` -------------------------------- ### Listen to Events Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Demonstrates how to subscribe to various events emitted by the embed client to react to user interactions and score state changes. ```APIDOC ## Listen to Events ### Description Demonstrates how to subscribe to various events emitted by the embed client to react to user interactions and score state changes. ### Method ```javascript embed.on(event, callback) ``` ### Parameters - **event** (string) - The name of the event to listen for. Supported events include: - `ready`: Fired when the embed is initialized and ready. - `scoreLoaded`: Fired when a score has been successfully loaded. - `play`: Fired when playback starts. - `pause`: Fired when playback is paused. - `stop`: Fired when playback stops. - `cursorPosition`: Fired when the cursor position changes. Provides position object. - `playbackPosition`: Fired during playback, indicating the current measure. Provides position object. - `measureDetails`: Fired when details about a measure are available. Provides details object (e.g., tempo). - `noteDetails`: Fired when details about a note are available. Provides note object. - **callback** (function) - The function to execute when the event is triggered. The callback receives event-specific data as arguments. ### Response No direct return value. The callback function is executed when the specified event occurs. ### Request Example ```javascript embed.on('ready', () => console.log('Embed ready')); embed.on('scoreLoaded', () => console.log('Score loaded')); embed.on('play', () => console.log('Playing')); embed.on('pause', () => console.log('Paused')); embed.on('stop', () => console.log('Stopped')); embed.on('cursorPosition', (pos) => console.log('Cursor:', pos)); embed.on('playbackPosition', (pos) => console.log('Playing measure:', pos.currentMeasure)); embed.on('measureDetails', (details) => console.log('Tempo:', details.tempo.bpm)); embed.on('noteDetails', (note) => console.log('Note:', note.pitches)); ``` ``` -------------------------------- ### Get Current Note Details Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Fetches details for the note currently under the cursor. This is useful for real-time interaction and display. ```typescript getNoteDetails(): Promise ``` ```typescript const noteDetails = await embed.getNoteDetails(); console.log(`Current note: ${noteDetails.pitches[0].step}`); console.log(`Is chord: ${noteDetails.isChord}`); console.log(`Lyrics: ${noteDetails.lyrics.map(l => l.text).join(' ')}`); ``` -------------------------------- ### getDisplayedParts() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Gets the list of parts that are currently visible in the score view. This allows checking which parts the user is seeing. ```APIDOC ## getDisplayedParts() ### Description Gets the currently visible parts. ### Method `async` ### Endpoint `embed.getDisplayedParts() ### Parameters None ### Response #### Success Response - `Promise`: An array of objects representing the currently displayed parts. ### Request Example ```typescript const displayed = await embed.getDisplayedParts(); console.log(`Showing ${displayed.length} parts`); ``` ``` -------------------------------- ### Performance Tips Source: https://github.com/flatio/embed-client/blob/master/_autodocs/quick-reference.md Offers advice on optimizing the performance of the Embed Client, such as batching queries and caching references. ```APIDOC ## Performance Tips 1. **Batch queries**: Combine multiple data queries when possible. 2. **Cache references**: Store UUIDs instead of re-querying. 3. **Debounce events**: Limit listener callback frequency. 4. **Lazy load**: Use `lazy: true` for off-screen embeds. 5. **Minimize redraws**: Set multiple properties before rendering. ### Example of Batch Querying ```typescript // Good: Single batch query const [parts, measures, details] = await Promise.all([ embed.getParts(), embed.getMeasuresUuids(), embed.getMeasureDetails() ]); // Avoid: Sequential queries const parts = await embed.getParts(); const measures = await embed.getMeasuresUuids(); const details = await embed.getMeasureDetails(); ``` ``` -------------------------------- ### Select Audio Source for Playback Source: https://github.com/flatio/embed-client/blob/master/_autodocs/configuration.md Choose the audio source for playback, options include Flat's synthesized playback, default system audio, or a custom identifier string. Defaults to 'playback'. ```typescript const embed = new Embed(container, { embedParams: { audioSource: 'playback' } }); ``` -------------------------------- ### Get Measure UUIDs Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves an array of unique identifiers for all measures in the score. Useful for referencing specific measures. ```typescript const uuids = await embed.getMeasuresUuids(); console.log(`First measure UUID: ${uuids[0]}`); ``` -------------------------------- ### getCursorPosition() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Gets the current cursor position in the score. This provides details about the measure, part, voice, and time position. ```APIDOC ## getCursorPosition() ### Description Gets the current cursor position in the score. ### Method `getCursorPosition(): Promise` ### Response #### Success Response (200) - **Promise** with position details ### Request Example ```typescript const pos = await embed.getCursorPosition(); console.log(`Cursor at measure ${pos.measureIdx + 1}`); console.log(`Part: ${pos.partIdx}, Voice: ${pos.voiceIdxInStaff}`); console.log(`Time: ${pos.timePos} seconds`); ``` ``` -------------------------------- ### Load and Play a Score Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Initializes the embed client with a score ID and application ID, then plays the score. It also demonstrates how to listen for the 'play' event. ```APIDOC ## Load and Play a Score ### Description Initializes the embed client with a score ID and application ID, then plays the score. It also demonstrates how to listen for the 'play' event. ### Method ```javascript new Embed(containerId, options) await embed.play() embed.on('play', callback) ``` ### Parameters #### Embed Constructor - **containerId** (string) - The ID of the HTML element to embed the score into. - **options** (object) - Configuration options for the embed. - **score** (string) - The ID of the score to load. - **embedParams** (object) - Additional parameters for embedding. - **appId** (string) - Required. Your Flat.io application ID. #### embed.play() No parameters. #### embed.on(event, callback) - **event** (string) - The name of the event to listen for (e.g., 'play'). - **callback** (function) - The function to execute when the event is triggered. ### Response #### embed.play() Returns a Promise that resolves when playback has started. #### embed.on() No direct return value, but triggers the callback function on event. ### Request Example ```javascript const embed = new Embed('container', { score: 'score-id', embedParams: { appId: 'app-id' } }); await embed.play(); embed.on('play', () => console.log('Playing')); ``` ``` -------------------------------- ### getPartVolume() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Gets the volume level for a specific part within the score. Requires the unique identifier (UUID) of the part. ```APIDOC ## getPartVolume(parameters: { partUuid: string }) ### Description Gets the volume level for a specific part. ### Method `getPartVolume(parameters: { partUuid: string })` ### Parameters #### Request Body - **partUuid** (`string`) - Required - UUID of the part ### Returns `Promise` volume (0-100) ### Example ```typescript const parts = await embed.getParts(); const volume = await embed.getPartVolume({ partUuid: parts[0].uuid }); ``` ``` -------------------------------- ### getMasterVolume() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Gets the current master volume level of the embedded score. The volume is returned as a number between 0 and 100. ```APIDOC ## getMasterVolume() ### Description Gets the current master volume level. ### Method `getMasterVolume()` ### Returns `Promise` volume (0-100) ### Example ```typescript const volume = await embed.getMasterVolume(); console.log(`Current volume: ${volume}%`); ``` ``` -------------------------------- ### Manage Parts and Volume Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Demonstrates how to mute, solo, and set the volume for individual parts within a score using their UUIDs. ```typescript const parts = await embed.getParts(); // Mute a specific part await embed.mutePart({ partUuid: parts[0].uuid }); // Solo a part await embed.setPartSoloMode({ partUuid: parts[0].uuid }); // Set part volume await embed.setPartVolume({ partUuid: parts[0].uuid, volume: 75 }); ``` -------------------------------- ### Custom Theming Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Explains how to apply custom themes to the embed player by specifying color options and disabling branding within the embed parameters. ```APIDOC ## Custom Theming ### Description Explains how to apply custom themes to the embed player by specifying color options and disabling branding within the embed parameters. ### Method ```javascript new Embed(containerId, options) ``` ### Parameters - **containerId** (string) - The ID of the HTML element to embed the score into. - **options** (object) - Configuration options for the embed. - **embedParams** (object) - Additional parameters for embedding. - **appId** (string) - Required. Your Flat.io application ID. - **themePrimary** (string) - Primary theme color (e.g., '#FF6B6B'). - **themePrimaryDark** (string) - Dark variant of the primary theme color. - **themeControlsBackground** (string) - Background color for controls. - **themeSlider** (string) - Color for the playback slider. - **branding** (boolean) - Set to `false` to hide Flat.io branding. ### Response N/A (Constructor does not return a value, but initializes the embed instance). ### Request Example ```javascript const embed = new Embed('container', { embedParams: { appId: 'app-id', themePrimary: '#FF6B6B', themePrimaryDark: '#E63946', themeControlsBackground: '#F1F1F1', themeSlider: '#4ECDC4', branding: false } }); ``` ``` -------------------------------- ### useTrack() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Enables a previously configured track. This allows switching between different audio or video tracks. ```APIDOC ## useTrack() ### Description Enables a previously configured track. ### Method `useTrack(parameters: { id: string }): Promise` ### Parameters #### Path Parameters - **parameters.id** (string) - Required - ID of the track to enable ### Response #### Success Response (200) - **Promise** when enabled ### Request Example ```typescript await embed.useTrack({ id: 'backing-track-1' }); // Switch between tracks await embed.useTrack({ id: 'practice-tempo' }); // Later... await embed.useTrack({ id: 'full-tempo' }); ``` ``` -------------------------------- ### Get Total Number of Measures Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves the total count of measures in the score. Use to understand the score's length. ```typescript const count = await embed.getNbMeasures(); console.log(`This score has ${count} measures`); ``` -------------------------------- ### getMetronomeMode() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Gets the current mode of the metronome. The mode is represented by a number: 0 for count-in only, 1 for continuous, and 2 for disabled. ```APIDOC ## getMetronomeMode() ### Description Gets the current metronome mode. ### Method `getMetronomeMode` ### Response #### Success Response - Returns `Promise`: The current metronome mode (0, 1, or 2). ### Request Example ```typescript const mode = await embed.getMetronomeMode(); switch(mode) { case 0: console.log('Count-in only'); break; case 1: console.log('Continuous'); break; case 2: console.log('Disabled'); break; } ``` ``` -------------------------------- ### Custom Theming for Embed Client Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Initializes the embed client with custom theme colors for primary elements, controls, and sliders. It also shows how to disable branding. ```typescript const embed = new Embed('container', { embedParams: { appId: 'app-id', themePrimary: '#FF6B6B', themePrimaryDark: '#E63946', themeControlsBackground: '#F1F1F1', themeSlider: '#4ECDC4', branding: false } }); ``` -------------------------------- ### Metadata & Configuration Methods Source: https://github.com/flatio/embed-client/blob/master/_autodocs/quick-reference.md Methods for retrieving and updating metadata and configuration. ```APIDOC ## Metadata & Configuration Methods ### `getFlatScoreMetadata()` #### Description Get the metadata for the currently loaded Flat score. ### Method `getFlatScoreMetadata()` ### Returns `Promise` ### `getEmbedConfig()` #### Description Get the current configuration of the embed instance. ### Method `getEmbedConfig()` ### Returns `Promise>` ### `setEditorConfig()` #### Description Update the editor settings for the embed. ### Method `setEditorConfig(editor: Record)` ### Returns `Promise` ``` -------------------------------- ### Get Metronome Mode Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves the current mode of the metronome. The mode can be 'Count-in only' (0), 'Continuous' (1), or 'Disabled' (2). ```typescript const mode = await embed.getMetronomeMode(); switch(mode) { case 0: console.log('Count-in only'); break; case 1: console.log('Continuous'); break; case 2: console.log('Disabled'); break; } ``` -------------------------------- ### Get Master Volume Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves the current master volume level of the score. Use this to check the overall audio volume. ```typescript const volume = await embed.getMasterVolume(); console.log(`Current volume: ${volume}%`); ``` -------------------------------- ### Wait for Embed to be Ready Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Use the `ready()` method to ensure the embed is fully initialized before performing other actions. This is often called internally. ```typescript const embed = new Embed('container', { score: 'score-id' }); await embed.ready(); console.log('Embed is ready for interactions'); ``` -------------------------------- ### Get Flat Score Metadata Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves metadata for scores loaded from Flat. Requires a Flat score to be loaded first. ```typescript await embed.loadFlatScore('56ae21579a127715a02901a6'); const metadata = await embed.getFlatScoreMetadata(); console.log(`Title: ${metadata.title}`); console.log(`Created by: ${metadata.user.username}`); console.log(`Composer: ${metadata.composer}`); ``` -------------------------------- ### Listen to Embed Client Events Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Demonstrates how to subscribe to various events emitted by the embed client to react to different states and actions, such as loading, playback, and cursor changes. ```typescript embed.on('ready', () => console.log('Embed ready')); embed.on('scoreLoaded', () => console.log('Score loaded')); embed.on('play', () => console.log('Playing')); embed.on('pause', () => console.log('Paused')); embed.on('stop', () => console.log('Stopped')); embed.on('cursorPosition', (pos) => console.log('Cursor:', pos)); embed.on('playbackPosition', (pos) => console.log('Playing measure:', pos.currentMeasure)); embed.on('measureDetails', (details) => console.log('Tempo:', details.tempo.bpm)); embed.on('noteDetails', (note) => console.log('Note:', note.pitches)); ``` -------------------------------- ### Get Total Number of Parts Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves the total count of parts (instruments) in the score. Use to understand the score's instrumentation. ```typescript const count = await embed.getNbParts(); console.log(`Score has ${count} instruments`); ``` -------------------------------- ### Embed Initialization in ES6 Project Source: https://github.com/flatio/embed-client/blob/master/README.md Initialize the Flat Embed client within an ES6 project by importing the Embed module and passing a container element and configuration. ```js import Embed from 'flat-embed'; const container = document.getElementById('embed-container'); const embed = new Embed(container, { score: '', embedParams: { appId: '', controlsPosition: 'bottom', }, }); ``` -------------------------------- ### Get Current Zoom Level Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves the current zoom level of the score display. The zoom ratio ranges from 0.5 to 3. ```typescript const zoom = await embed.getZoom(); console.log(`Current zoom: ${zoom * 100}%`); ``` -------------------------------- ### goRight() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Moves the cursor to the next note or rest. Optionally, this can be done silently without playing the note at the new position. ```APIDOC ## goRight() ### Description Moves cursor to the next note/rest. ### Method `goRight(mute?: boolean): Promise` ### Parameters #### Path Parameters - **mute** (boolean) - Optional - Default: `false` - If false, plays the note at new position ### Response #### Success Response (200) - **Promise** when moved ### Request Example ```typescript await embed.goRight(); // Move and play await embed.goRight(true); // Move silently // Navigate through score for (let i = 0; i < 10; i++) { await embed.goRight(true); } ``` ``` -------------------------------- ### Enable Video Fit to Width Source: https://github.com/flatio/embed-client/blob/master/_autodocs/configuration.md Scale the video to automatically fit the container's width. Set to 'true' to enable this behavior. ```typescript const embed = new Embed(container, { embedParams: { videoFitWidth: true } }); ``` -------------------------------- ### Stop Score Playback Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Stops score playback and resets the position to the beginning. Use this to completely halt playback and return to the start. ```typescript await embed.stop(); await embed.play(); // Starts from beginning ``` -------------------------------- ### Get Current Measure Details Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves comprehensive information about the measure currently at the cursor. Includes time signature, key signature, and tempo. ```typescript const details = await embed.getMeasureDetails(); console.log(`Time signature: ${details.time.beats}/${details.time['beat-type']}`); console.log(`Key: ${details.key.fifths} sharps/flats`); console.log(`Tempo: ${details.tempo.bpm} BPM`); ``` -------------------------------- ### Lazy Initialization of Embed Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Illustrates that explicit calls to 'ready()' are optional as the embed automatically handles readiness before other methods are invoked. ```typescript // No need to call ready() explicitly const embed = new Embed('container', { score: 'id' }); await embed.play(); // Automatically waits for ready ``` -------------------------------- ### Get Currently Visible Parts Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves an array of parts that are currently visible in the score view. Use to check the current display state. ```typescript const displayed = await embed.getDisplayedParts(); console.log(`Showing ${displayed.length} parts`); ``` -------------------------------- ### Get All Instrument Parts Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves information about all instrument parts in the score. Useful for identifying parts by name, instrument, or UUID for subsequent operations. ```typescript const parts = await embed.getParts(); parts.forEach(part => { console.log(`${part.name}: ${part.uuid}`); }); const violin = parts.find(p => p.instrument === 'violin'); ``` -------------------------------- ### Embed Constructor Source: https://github.com/flatio/embed-client/blob/master/_autodocs/quick-reference.md Initializes a new Embed instance, targeting an HTML element and accepting optional configuration parameters. ```APIDOC ## new Embed() ### Description Initializes a new Embed instance. It can target an existing iframe element, a container element, or a string selector for an element. Optional parameters allow for customization of the embed's appearance and behavior. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **element** (HTMLIFrameElement | HTMLElement | string) - Required - The target element or selector for the embed. * **parameters** (object) - Optional - Configuration options for the embed. * **score** (string) - Optional - The ID of the score to load. * **width** (string) - Optional - The width of the embed. * **height** (string) - Optional - The height of the embed. * **baseUrl** (string) - Optional - The base URL for the embed. * **isCustomUrl** (string) - Optional - Indicates if a custom URL is used. * **lazy** (boolean) - Optional - Enables lazy loading. * **embedParams** (object) - Optional - Additional parameters for embedding. * **appId** (string) - Optional - The application ID. * **mode** ('view' | 'edit') - Optional - The embed mode. * **userId** (string) - Optional - The user ID. * **sharingKey** (string) - Optional - The sharing key. * **locale** (FlatLocales) - Optional - The locale for the embed. * **layout** ('responsive' | 'page' | 'track') - Optional - The layout of the embed. * **zoom** ('auto' | number) - Optional - The zoom level. ``` -------------------------------- ### Enable MIDI Output Controls Source: https://github.com/flatio/embed-client/blob/master/_autodocs/configuration.md Enable or disable the MIDI output controls within the embed. Set to 'true' to show MIDI controls. ```typescript const embed = new Embed(container, { embedParams: { MIDI: true // Enable MIDI controls } }); ``` -------------------------------- ### Get Current Cursor Position Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves the current cursor position within the score, including measure, part, voice, and time information. ```typescript const pos = await embed.getCursorPosition(); console.log(`Cursor at measure ${pos.measureIdx + 1}`); console.log(`Part: ${pos.partIdx}, Voice: ${pos.voiceIdxInStaff}`); console.log(`Time: ${pos.timePos} seconds`); ``` -------------------------------- ### Export Score as MusicXML Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Exports the current score in MusicXML format. Use the `compressed` option to get a compressed MXL file as a Uint8Array. ```typescript const xml = await embed.getMusicXML(); console.log(xml); // ``` -------------------------------- ### Control Playback Speed & Metronome Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Allows control over the playback speed of the score and the mode of the metronome. Includes methods to set and get these values. ```APIDOC ## Control Playback Speed & Metronome ### Description Allows control over the playback speed of the score and the mode of the metronome. Includes methods to set and get these values. ### Method ```javascript await embed.setPlaybackSpeed(speed) await embed.getPlaybackSpeed() await embed.setMetronomeMode(mode) await embed.getMetronomeMode() ``` ### Parameters #### embed.setPlaybackSpeed(speed) - **speed** (number) - The desired playback speed, where 1.0 is normal speed. #### embed.getPlaybackSpeed() No parameters. #### embed.setMetronomeMode(mode) - **mode** (number) - The metronome mode. `1` for continuous. #### embed.getMetronomeMode() No parameters. ### Response #### embed.setPlaybackSpeed() Returns a Promise that resolves when the playback speed has been set. #### embed.getPlaybackSpeed() Returns a Promise that resolves with the current playback speed. #### embed.setMetronomeMode() Returns a Promise that resolves when the metronome mode has been set. #### embed.getMetronomeMode() Returns a Promise that resolves with the current metronome mode. ### Request Example ```javascript // Slow down for practice await embed.setPlaybackSpeed(0.75); // Enable metronome await embed.setMetronomeMode(1); // Continuous // Get current settings const speed = await embed.getPlaybackSpeed(); const metro = await embed.getMetronomeMode(); ``` ``` -------------------------------- ### Configure Embed Layout Source: https://github.com/flatio/embed-client/blob/master/_autodocs/configuration.md Set the score display mode to 'responsive', 'page', or 'track'. 'responsive' adapts to container width, 'page' displays like a PDF, and 'track' shows a single horizontal system. ```typescript const embed = new Embed(container, { embedParams: { layout: 'page' // Full page layout } }); ``` -------------------------------- ### Run All Tests Source: https://github.com/flatio/embed-client/blob/master/test/README.md Execute all tests using the pnpm test command. This command runs Vitest in browser mode. ```bash pnpm test ``` -------------------------------- ### Performance Tip: Batch Queries Source: https://github.com/flatio/embed-client/blob/master/_autodocs/quick-reference.md Improve performance by fetching multiple data points in a single asynchronous operation using Promise.all, rather than sequential calls. ```typescript // Good: Single batch query const [parts, measures, details] = await Promise.all([ embed.getParts(), embed.getMeasuresUuids(), embed.getMeasureDetails() ]); // Avoid: Sequential queries const parts = await embed.getParts(); const measures = await embed.getMeasuresUuids(); const details = await embed.getMeasureDetails(); ``` -------------------------------- ### Get Current Playback Speed Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves the current playback speed multiplier. The value ranges from 0.2 to 2.0, with 1.0 representing normal speed. ```typescript const speed = await embed.getPlaybackSpeed(); console.log(`Playing at ${speed * 100}% speed`); ``` -------------------------------- ### Get Part Volume Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves the volume level for a specific part of the score using its UUID. Use this to check the volume of an individual instrument or voice. ```typescript const parts = await embed.getParts(); const volume = await embed.getPartVolume({ partUuid: parts[0].uuid }); ``` -------------------------------- ### getEmbedConfig() Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Fetches the complete embed configuration, including settings for display, permissions, and features available in the embeddable player. ```APIDOC ## getEmbedConfig() ### Description Gets the complete embed configuration including display settings, permissions, and features. ### Method `getEmbedConfig(): Promise>` ### Parameters None ### Returns `Promise>` with config object. ### Request Example ```typescript const config = await embed.getEmbedConfig(); console.log(`Mode: ${config.mode}`); console.log(`Controls enabled: ${config.controlsPlay}`); ``` ``` -------------------------------- ### Load Different Score Formats Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Demonstrates loading scores into the embed client from various formats including MusicXML (string and binary), MIDI, ABC Notation, and JSON. ```APIDOC ## Load Different Score Formats ### Description Demonstrates loading scores into the embed client from various formats including MusicXML (string and binary), MIDI, ABC Notation, and JSON. ### Method ```javascript await embed.loadMusicXML(data) await embed.loadMIDI(data) await embed.loadABC(data) await embed.loadJSON(data) ``` ### Parameters #### embed.loadMusicXML(data) - **data** (string | Uint8Array) - MusicXML content as a string or a binary buffer (for MXL). #### embed.loadMIDI(data) - **data** (Uint8Array) - MIDI file content as a binary buffer. #### embed.loadABC(data) - **data** (string) - ABC notation content as a string. #### embed.loadJSON(data) - **data** (object) - Score data in JSON format. ### Response All `load` methods return a Promise that resolves when the score has been loaded. ### Request Example ```javascript // MusicXML from string await embed.loadMusicXML('...'); // MusicXML from binary (MXL) const mxlBuffer = await fetch('score.mxl').then(r => r.arrayBuffer()); await embed.loadMusicXML(new Uint8Array(mxlBuffer)); // MIDI const midiBuffer = await fetch('song.mid').then(r => r.arrayBuffer()); await embed.loadMIDI(new Uint8Array(midiBuffer)); // ABC Notation await embed.loadABC('X:1\nT:Example\nM:4/4\nK:C\nCDEF|'); // JSON const scoreJson = await fetch('score.json').then(r => r.json()); await embed.loadJSON(scoreJson); ``` ``` -------------------------------- ### Embed Initialization Options Source: https://github.com/flatio/embed-client/blob/master/README.md Options available when instantiating the Flat.Embed object. The `embedParams.appId` is required for most functionalities. ```APIDOC ## Options and URL Parameters When instantiating `Flat.Embed`, you can pass options in the second parameter. To use the different methods available and events subscriptions, you will need to pass at least `embedParams.appId`. | Option | Description | Values | | :------------ | :-------------------------------------------------- | :------------------------------------------------------------------------------ | | `score` | The score identifier that will load initially | Unique score id | | `width` | The width of your embed | A width of the embed | | `height` | The height of your embed | A height of the embed | | `embedParams` | Object containing the loading options for the embed | [Any URL parameters](https://flat.io/developers/docs/embed/url-parameters.html) | | `lazy` | Add a `loading="lazy"` attribute to the iframe | A boolean to enable the lazy-loading | ``` -------------------------------- ### Export to PDF Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Retrieves all parts of a score and then exports a specified part to a PDF document. It demonstrates how to get part UUIDs and set PDF export options. ```APIDOC ## Export to PDF ### Description Retrieves all parts of a score and then exports a specified part to a PDF document. It demonstrates how to get part UUIDs and set PDF export options. ### Method ```javascript await embed.getParts() await embed.getPDF(options) ``` ### Parameters #### embed.getParts() No parameters. #### embed.getPDF(options) - **options** (object) - Options for PDF export. - **parts** (array) - An array of part UUIDs to include in the PDF. - **isConcertPitch** (boolean) - Optional. Whether to export in concert pitch. ### Response #### embed.getParts() Returns an array of part objects, each containing a `uuid` property. #### embed.getPDF() Returns a Promise that resolves with the PDF data as an ArrayBuffer. ### Request Example ```javascript const parts = await embed.getParts(); const pdfData = await embed.getPDF({ parts: [parts[0].uuid], isConcertPitch: true }); const blob = new Blob([pdfData], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); ``` ``` -------------------------------- ### Load Different Score Formats Source: https://github.com/flatio/embed-client/blob/master/_autodocs/README.md Shows how to load scores into the embed client from various formats including MusicXML (string and binary), MIDI, ABC Notation, and JSON. ```typescript // MusicXML from string await embed.loadMusicXML('...'); // MusicXML from binary (MXL) const mxlBuffer = await fetch('score.mxl').then(r => r.arrayBuffer()); await embed.loadMusicXML(new Uint8Array(mxlBuffer)); // MIDI const midiBuffer = await fetch('song.mid').then(r => r.arrayBuffer()); await embed.loadMIDI(new Uint8Array(midiBuffer)); // ABC Notation await embed.loadABC('X:1\nT:Example\nM:4/4\nK:C\nCDEF|'); // JSON const scoreJson = await fetch('score.json').then(r => r.json()); await embed.loadJSON(scoreJson); ``` -------------------------------- ### Enable Configured Track Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Enables a previously configured track by its ID. Use this to switch between different backing tracks or audio sources. ```typescript await embed.useTrack({ id: 'backing-track-1' }); // Switch between tracks await embed.useTrack({ id: 'practice-tempo' }); // Later... await embed.useTrack({ id: 'full-tempo' }); ``` -------------------------------- ### Get Reverb Level for a Part Source: https://github.com/flatio/embed-client/blob/master/_autodocs/api-reference/embed.md Retrieves the current reverb level applied to a specific part. Returns a number between 0 and 100. Requires the part's UUID. ```typescript const parts = await embed.getParts(); const reverb = await embed.getPartReverb({ partUuid: parts[0].uuid }); ```