Flat Sheet Music Embed Client
Use this JavaScript Client to interact and receive events from our Sheet Music Embed.
If you have any feedback or questions regarding this product, please feel free to contact our developers support.
Installation
You can install our Embed Client using npm or yarn:
npm install flat-embed
yarn add flat-embed
Or use the latest version hosted on our CDN:
<script src="https://prod.flat-cdn.com/embed-js/v1.0.0/embed.min.js"></script>
Getting Started
The simplest way to get started is to pass a DOM element to our embed that will be used as container. By default, this one will completely fit its container:
<div id="embed-container"></div>
<script src="https://prod.flat-cdn.com/embed-js/v1.0.0/embed.min.js"></script>
<script>
var container = document.getElementById('embed-container');
var embed = new Flat.Embed(container, {
score: '<score-id-you-want-to-load>',
embedParams: {
appId: '<your-app-id>',
controlsPosition: 'bottom',
}
});
</script>
>> Open this demo in JSFiddle
App ID
Our Embed JS API requires an App ID (appId
) to use it:
- In development, you can try and use this client without limits on
localhost
/*.localhost
. - To use it in production or with a custom domain, create a new app on our website, then go to the Embed > Settings and add your domains to the whitelist. Your app ID will also be displayed on this page.
Embed construction
DOM element or existing iframe
When instantiating Flat.Embed
, the first argument will always refer to a DOM element. It can take:
- A DOM element (e.g. selected using
document.getElementById('embed-container')
). - The string identifier of the element (e.g.
"embed-container"
). - A jQuery element (e.g. selected using
$('#embed-container')
). If multiple elements match the selection, the client will take the first one selected. - An existing embed iframe element. In this case, this one will need to have our JS API loaded using the query string
jsapi=true
.
If you instance different Flat.Embed
for the same element, you will always get the same instance of the object.
Options and URL parameters
When instantiating Flat.Embed
, you can pass options in the second parameter. In order to use the different methods available and events subscriptions, you will need to pass at least embedParams.appId
.
Option | Description | Values | Default |
---|
score | The score identifier that will load initially | Unique score id | blank |
width | The width of your embed | A width of the embed | 100% |
height | The height of your embed | A height of the embed | 100% |
embedParams | Object containing the loading options for the embed | Any URL parameters | {} |
JavaScript API
Viewer Methods
You can call the methods using any Flat.Embed
object. By default, the methods (except on
and off
) return a Promise that will be resolved once the method is called, the value is set or get:
var embed = new Flat.Embed('container');
embed.loadFlatScore('12234').then(function () {
console.log('Score loaded');
}).catch(function (err) {
console.log('Error', err);
});
ready(): Promise<void, Error>
Promises resolved when the embed is loaded and the JavaScript API is ready to use. All the methods will implicitly use this method, so you don't have to worry about waiting the loading before calling the different methods.
embed.ready().then(function() {
});
on(event: string, callback: function): void
Add an event listener for the specified event. When receiving the event, the client will call the specified function with zero or one parameters depending of the event received.
embed.on('playbackPosition', function (position) {
console.log(position);
});
off(event: string, callback?: function): void
Remove an event listener for the specified event. If no callback
is specified, all the listener for the event will be removed.
function positionChanged(position) {
console.log(position);
embed.off('play', positionChanged);
embed.off('play');
};
embed.on('positionChanged', positionChanged);
getEmbedConfig(): Promise<object, Error>
Fetch the global config of the embed. This will include the URL parameters, the editor config and the default config set by the embed.
embed.getEmbedConfig().then(function (config) {
console.log(config);
});
loadFlatScore(id: string): Promise<void, ApiError>
Load a score hosted on Flat using its identifier. For example to load https://flat.io/score/56ae21579a127715a02901a6-house-of-the-rising-sun
, you can call:
embed.loadFlatScore('56ae21579a127715a02901a6').then(function () {
}).catch(function (error) {
});
loadMusicXML(score: mixed): Promise<void, Error>
Load a MusicXML score, compressed (MXL) or not (plain XML):
fetch('https://api.flat.io/v2/scores/56ae21579a127715a02901a6/revisions/last/mxl')
.then(function (response) {
return response.arrayBuffer();
})
.then(function (mxl) {
return embed.loadMusicXML(mxl);
})
.then(function () {
})
.catch(function (error) {
});
loadJSON(score: object): Promise<void, Error>
Load a score using Flat's JSON Format
fetch('https://api.flat.io/v2/scores/56ae21579a127715a02901a6/revisions/last/json')
.then(function (response) {
return response.json();
})
.then(function (json) {
return embed.loadJSON(json);
})
.then(function () {
})
.catch(function (error) {
});
getMusicXML(options?: object): Promise<string|Uint8Array, Error>
Convert the current displayed score into a MusicXML file, compressed (.mxl
) or not (.xml
).
embed.getMusicXML().then(function (xml) {
console.log(xml);
});
Example: Retrieve the score as a compressed MusicXML, then convert it to a Blob and download it:
embed.getMusicXML({ compressed: true }).then(function (buffer) {
var blobUrl = window.URL.createObjectURL(new Blob([buffer], {
type: 'application/vnd.recordare.musicxml+xml'
}));
var a = document.createElement('a');
a.href = blobUrl;
a.download = 'My Music Score.mxl';
document.body.appendChild(a);
a.style = 'display: none';
a.click();
a.remove();
});
getJSON(): object
Get the data of the score in the "Flat JSON" format (a MusicXML-like as a JavaScript object).
embed.getJSON().then(function (data) {
console.log(data);
}).catch(function (error) {
});
getPNG(options?: object): Promise<string|Uint8Array, Error>
Get the current displayed score as a PNG file
embed.getPNG().then(function (png) {
console.log(png);
});
embed.getPNG({result: 'dataURL'}).then(function (png) {
console.log(png);
});
getMIDI(): Promise<Uint8Array, Error>
Get the current displayed score as a MIDI file
embed.getMIDI().then(function (midi) {
console.log(midi);
});
getScoreMeta(): object
Get the score metadata of the hosted score. The object will have the same format that the one returned by our API GET /v2/scores/{score}
.
embed.getScoreMeta().then(function (metadata) {
console.log(metadata);
}).catch(function (error) {
});
fullscreen(state: bool): Promise<void, Error>
Display the embed in fullscreen (state = true
) or return to the regular display (state = false
).
embed.fullscreen(true).then(function () {
});
play(): Promise<void, Error>
Load the playback and play the score.
embed.play().then(function () {
});
pause(): Promise<void, Error>
Pause the playback
embed.pause().then(function () {
});
stop(): Promise<void, Error>
Stop the playback
embed.stop().then(function () {
});
mute(): Promise<void, Error>
Mute the playback
embed.mute().then(function () {
});
print(): Promise<void, Error>
Print the score
embed.print().then(function () {
}).catch(function (error) {
});
getZoom(): Promise<number, Error>
Get the current zoom ration applied for the score (between 0.5 and 3).
embed.getZoom().then(function (zoom) {
console.log(zoom);
});
setZoom(number): Promise<number, Error>
Set a new zoom ration for the display (between 0.5 and 3).
embed.setZoom(2).then(function (zoom) {
console.log(zoom);
});
getAutoZoom(): Promise(<boolean, Error>)
Get the state of the auto-zoom mode. Auto-zoom is enabled by default for page mode or when the URL parameter zoom
is set to auto
.
This getter will return true
if the auto-zoom is enabled, and false
when disabled. Setting a zoom value with setZoom
will disable this mode.
embed.getAutoZoom().then(function (state) {
console.log(state);
});
setAutoZoom(boolean): Promise(<boolean, Error>)
Enable (true
) or disable (false
) the auto-zoom. Auto-zoom is enabled by default for page mode or when the URL parameter zoom
is set to auto
. Setting a zoom value with setZoom
will disable this mode.
embed.setAutoZoom(false).then(function (state) {
console.log(state);
});
focusScore(): Promise(<void, Error>)
Unlike the web version on https://flat.io, the embed does't catch the focus. This avoids to mess with the parent window, and avoid the browser to do a forced scrolling to the embed iframe.
If the end-user's goal is the usage of the embed to play or write notation, you can use this method to set the focus on the score and allowing they to use the keyboard bindings.
embed.focusScore().then(function () {
});
getCursorPosition(): Promise(<object, Error>)
Return the current position of the cursor (on a specific note).
embed.getCursorPosition().then(function (position) {
});
setCursorPosition(position: object): Promise(<object, Error>)
Set the current position of the cursor (on a specific note).
embed.setCursorPosition({
partIdx: 0,
staffIdx: 1,
voiceIdx: 0,
measureIdx: 2,
noteIdx: 1
}).then(function (position) {
});
Editor Methods
You can enable the editor mode by setting the mode
to edit
when creating the embed:
var embed = new Flat.Embed(container, {
embedParams: {
appId: '<your-app-id>',
mode: 'edit'
}
});
Events API
Events are broadcasted following actions made by the end user or you with the JavaScript API. You can subscribe to an event using the method on
, and unsubscribe using off
. When an event includes some data, this data will be available in the first parameter of the listener callback.
Event: scoreLoaded
This event is triggered once a new score has been loaded. This event doesn't include any data.
Event: cursorPosition
This event is triggered when the position of the user's cursor changes.
{
"partIdx": 0,
"staffIdx": 1,
"voiceIdx": 0,
"measureIdx": 2,
"noteIdx": 1
}
Event: rangeSelection
This event is triggered when a range of notes is selected or the selection changed.
{
"from": {
"partIdx": 0,
"measureIdx": 1,
"staffIdx": 0,
"voiceIdx": 0,
"noteIdx": 2
},
"to": {
"partIdx": 0,
"measureIdx": 3,
"staffIdx": 0,
"voiceIdx": 0,
"noteIdx": 5
}
}
Event: fullscreen
This event is triggered when the state of the fullscreen changed. The callback will take a boolean as the first parameter that will be true
if the fullscreen mode is enabled, and false
is the display is back to normal (fullscreen exited).
Event: play
This event is triggered when you or the end-user starts the playback. This event doesn't include any data.
Event: pause
This event is triggered when you or the end-user pauses the playback. This event doesn't include any data.
Event: stop
This event is triggered when you or the end-user stops the playback. This event doesn't include any data.
Event: playbackPosition
This event is triggered when the playback slider moves. It is usually triggered at the beginning of every measure and will contain an object with information regarding the position of the playback in the score:
{
"beat": "4",
"beatType": "4",
"tempo": 120,
"currentMeasure": 1,
"timePerMeasure": 2
}