index.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. import { OpenSheetMusicDisplay } from '../src/OpenSheetMusicDisplay/OpenSheetMusicDisplay';
  2. import { BackendType } from '../src/OpenSheetMusicDisplay/OSMDOptions';
  3. import { PlaybackManager, LinearTimingSource, BasicAudioPlayer, ControlPanel } from '../src/Playback';
  4. import * as jsPDF from '../node_modules/jspdf/dist/jspdf.es.min';
  5. import * as svg2pdf from '../node_modules/svg2pdf.js/dist/svg2pdf.umd.min';
  6. import { TransposeCalculator } from '../src/Plugins/Transpose/TransposeCalculator';
  7. /*jslint browser:true */
  8. (function () {
  9. "use strict";
  10. var openSheetMusicDisplay;
  11. var sampleFolder = "",
  12. samples = {
  13. "playerdemo.musicxml": "playerdemo.musicxml",
  14. "Beethoven, L.v. - An die ferne Geliebte": "Beethoven_AnDieFerneGeliebte.xml",
  15. "Clementi, M. - Sonatina Op.36 No.1 Pt.1": "MuzioClementi_SonatinaOpus36No1_Part1.xml",
  16. "Clementi, M. - Sonatina Op.36 No.1 Pt.2": "MuzioClementi_SonatinaOpus36No1_Part2.xml",
  17. "Clementi, M. - Sonatina Op.36 No.3 Pt.1": "MuzioClementi_SonatinaOpus36No3_Part1.xml",
  18. "Clementi, M. - Sonatina Op.36 No.3 Pt.2": "MuzioClementi_SonatinaOpus36No3_Part2.xml",
  19. "Bach, J.S. - Praeludium in C-Dur BWV846 1": "JohannSebastianBach_PraeludiumInCDur_BWV846_1.xml",
  20. "Bach, J.S. - Air": "JohannSebastianBach_Air.xml",
  21. "Gounod, C. - Méditation": "CharlesGounod_Meditation.xml",
  22. "Haydn, J. - Concertante Cello": "JosephHaydn_ConcertanteCello.xml",
  23. "Joplin, S. - Elite Syncopations": "ScottJoplin_EliteSyncopations.xml",
  24. "Joplin, S. - The Entertainer": "ScottJoplin_The_Entertainer.xml",
  25. "Mozart, W.A. - An Chloe": "Mozart_AnChloe.xml",
  26. "Mozart, W.A. - Das Veilchen": "Mozart_DasVeilchen.xml",
  27. "Mozart, W.A. - Clarinet Quintet (Excerpt)": "Mozart_Clarinet_Quintet_Excerpt.mxl",
  28. "Mozart, W.A. - String Quartet in G, K. 387, 1st Mvmt Excerpt": "Mozart_String_Quartet_in_G_K._387_1st_Mvmnt_excerpt.musicxml",
  29. "Mozart/Holzer - Land der Berge (national anthem of Austria)": "Land_der_Berge.musicxml",
  30. "OSMD Function Test - All": "OSMD_function_test_all.xml",
  31. "OSMD Function Test - Accidentals": "OSMD_function_test_accidentals.musicxml",
  32. "OSMD Function Test - Autobeam": "OSMD_function_test_autobeam.musicxml",
  33. "OSMD Function Test - Auto-/Custom-Coloring": "OSMD_function_test_auto-custom-coloring-entchen.musicxml",
  34. "OSMD Function Test - Bar lines": "OSMD_function_test_bar_lines.musicxml",
  35. "OSMD Function Test - Chord Symbols": "OSMD_function_test_chord_symbols.musicxml",
  36. "OSMD Function Test - Chord Spacing": "OSMD_function_test_chord_spacing.mxl",
  37. "OSMD Function Test - Chord Symbols - Various Chords": "OSMD_function_test_chord_tests_various.musicxml",
  38. "OSMD Function Test - Chord Symbols - BrookeWestSample": "BrookeWestSample.mxl",
  39. "OSMD Function Test - Color (from XML)": "OSMD_function_test_color.musicxml",
  40. "OSMD Function Test - Container height (compacttight mode)": "OSMD_Function_Test_Container_height.musicxml",
  41. "OSMD Function Test - Drumset": "OSMD_function_test_drumset.musicxml",
  42. "OSMD Function Test - Drums on one Line": "OSMD_Function_Test_Drums_one_line_snare_plus_piano.musicxml",
  43. "OSMD Function Test - Expressions": "OSMD_function_test_expressions.musicxml",
  44. "OSMD Function Test - Expressions Overlap": "OSMD_function_test_expressions_overlap.musicxml",
  45. "OSMD Function Test - Grace Notes": "OSMD_function_test_GraceNotes.xml",
  46. "OSMD Function Test - Metronome Marks": "OSMD_function_test_metronome_marks.mxl",
  47. "OSMD Function Test - Multiple Rest Measures": "OSMD_function_test_multiple_rest_measures.musicxml",
  48. "OSMD Function Test - Invisible Notes": "OSMD_function_test_invisible_notes.musicxml",
  49. "OSMD Function Test - Notehead Shapes": "OSMD_function_test_noteheadShapes.musicxml",
  50. "OSMD Function Test - Ornaments": "OSMD_function_test_Ornaments.xml",
  51. "OSMD Function Test - Pedals": "OSMD_Function_Test_Pedals.musicxml",
  52. "OSMD Function Test - Selecting Measures To Draw": "OSMD_function_test_measuresToDraw_Beethoven_AnDieFerneGeliebte.xml",
  53. "OSMD Function Test - System and Page Breaks": "OSMD_Function_Test_System_and_Page_Breaks_4_pages.mxl",
  54. "OSMD Function Test - Tabulature": "OSMD_Function_Test_Tabulature_hayden_study_1.mxl",
  55. "OSMD Function Test - Tabulature MultiBends": "OSMD_Function_Test_Tablature_Multibends.musicxml",
  56. "OSMD Function Test - Tabulature All Effects": "OSMD_Function_Test_Tablature_Alleffects.musicxml",
  57. "OSMD Function Test - Tremolo": "OSMD_Function_Test_Tremolo_2bars.musicxml",
  58. "OSMD Function Test - Labels": "OSMD_Function_Test_Labels.musicxml",
  59. "OSMD Function Test - High Slur Test": "test_slurs_highNotes.musicxml",
  60. "OSMD Function Test - Auto Multirest Measures Single Staff": "Test_Auto_Multirest_1.musicxml",
  61. "OSMD Function Test - Auto Multirest Measures Multiple Staves": "Test_Auto_Multirest_2.musicxml",
  62. "OSMD Function Test - String number collisions": "test_string_number_collisions.musicxml",
  63. "OSMD Function Test - Repeat Stave Connectors": "OSMD_function_Test_Repeat.musicxml",
  64. "OSMD Function Test - Trill Lines": "OSMD_Trill_Line_Function_Test.musicxml",
  65. "OSMD Function Test - Voice Alignment": "OSMD_Function_Test_Voice_Alignment.musicxml",
  66. "Schubert, F. - An Die Musik": "Schubert_An_die_Musik.xml",
  67. "Actor, L. - Prelude (Large Sample, loading time)": "ActorPreludeSample.xml",
  68. "Actor, L. - Prelude (Large, No Print Part Names)": "ActorPreludeSample_PartName.xml",
  69. "Anonymous - Saltarello": "Saltarello.mxl",
  70. "Debussy, C. - Mandoline": "Debussy_Mandoline.xml",
  71. "Levasseur, F. - Parlez Mois": "Parlez-moi.mxl",
  72. "Schumann, R. - Dichterliebe": "Dichterliebe01.xml",
  73. "Telemann, G.P. - Sonate-Nr.1.1-Dolce": "TelemannWV40.102_Sonate-Nr.1.1-Dolce.xml",
  74. "Telemann, G.P. - Sonate-Nr.1.2-Allegro": "TelemannWV40.102_Sonate-Nr.1.2-Allegro-F-Dur.xml",
  75. },
  76. comments = {
  77. "Beethoven_AnDieFerneGeliebte.xml": ["Beethoven_AnDieFerneGeliebte_comments.xml", "Beethoven_AnDieFerneGeliebte_comments_2.xml"]
  78. },
  79. zoom = 1.0,
  80. // HTML Elements in the page
  81. divControls,
  82. zoomControls,
  83. header,
  84. err,
  85. error_tr,
  86. canvas,
  87. selectSample,
  88. selectBounding,
  89. skylineDebug,
  90. bottomlineDebug,
  91. zoomIns,
  92. zoomOuts,
  93. zoomDivs,
  94. custom,
  95. previousCursorBtn,
  96. nextCursorBtn,
  97. resetCursorBtn,
  98. followCursorCheckbox,
  99. showCursorBtn,
  100. hideCursorBtn,
  101. backendSelect,
  102. backendSelectDiv,
  103. debugReRenderBtn,
  104. debugClearBtn,
  105. selectPageSizes,
  106. printPdfBtns,
  107. transpose,
  108. transposeBtn,
  109. performanceMode,
  110. performanceModeBtn,
  111. playbackControlsButton,
  112. playbackControl;
  113. //unmuteButton;
  114. // manage option setting and resetting for specific samples, e.g. in the autobeam sample autobeam is set to true, otherwise reset to previous state
  115. // TODO design a more elegant option state saving & restoring system, though that requires saving the options state in OSMD
  116. var minMeasureToDrawStashed = 1;
  117. var maxMeasureToDrawStashed = Number.MAX_SAFE_INTEGER;
  118. var measureToDrawRangeNeedsReset = false;
  119. var drawingParametersStashed = "default";
  120. var drawingParametersNeedsReset = false;
  121. var autobeamOptionNeedsReset = false;
  122. var autobeamOptionStashedValue = false;
  123. var autoCustomColoringOptionNeedsReset = false;
  124. var autoCustomColoringOptionStashedValue = false;
  125. var drawPartNamesOptionStashedValue = true;
  126. var drawPartAbbreviationsStashedValue = true;
  127. var drawPartNamesOptionNeedsReset = false;
  128. var pageBreaksOptionStashedValue = false;
  129. var pageBreaksOptionNeedsReset = false;
  130. var systemBreaksOptionStashedValue = false; // reset handled by pageBreaksOptionNeedsReset
  131. var showControls = true;
  132. var showExportPdfControl = false;
  133. var showPageFormatControl = false;
  134. var showZoomControl = true;
  135. var showHeader = true;
  136. var showDebugControls = false;
  137. document.title = "OSMD Audio Player Demo";
  138. function iOSDetected() {
  139. // according to https://stackoverflow.com/a/9039885/10295942
  140. return [
  141. 'iPad Simulator',
  142. 'iPhone Simulator',
  143. 'iPod Simulator',
  144. 'iPad',
  145. 'iPhone',
  146. 'iPod'
  147. ].includes(navigator.platform)
  148. // note that .platform was apparently only accidentally marked deprecated,
  149. // see https://stackoverflow.com/a/47599911/10295942
  150. // iPad on iOS 13 detection
  151. || (navigator.userAgent.includes("Mac") && "ontouchend" in document)
  152. // note that some people recommend just checking userAgent instead of platform, but
  153. // "userAgent gives false positives because some vendors fake it to mimic Apple devices for whatever reasons"
  154. }
  155. // Initialization code
  156. function init() {
  157. var name, option;
  158. // Handle window parameter
  159. var paramEmbedded = findGetParameter('embedded');
  160. var paramShowControls = findGetParameter('showControls');
  161. var paramShowPageFormatControl = findGetParameter('showPageFormatControl');
  162. var paramShowExportPdfControl = findGetParameter('showExportPdfControl');
  163. var paramShowZoomControl = findGetParameter('showZoomControl');
  164. var paramShowHeader = findGetParameter('showHeader');
  165. var paramZoom = findGetParameter('zoom');
  166. var paramOverflow = findGetParameter('overflow');
  167. var paramOpenUrl = findGetParameter('openUrl');
  168. var paramDebugControls = findGetParameter('debugControls');
  169. var paramCompactMode = findGetParameter('compactMode');
  170. var paramMeasureRangeStart = findGetParameter('measureRangeStart');
  171. var paramMeasureRangeEnd = findGetParameter('measureRangeEnd');
  172. var paramPageFormat = findGetParameter('pageFormat');
  173. var paramPageBackgroundColor = findGetParameter('pageBackgroundColor');
  174. var paramBackendType = findGetParameter('backendType');
  175. var paramPageWidth = findGetParameter('pageWidth');
  176. var paramPageHeight = findGetParameter('pageHeight');
  177. var paramHorizontalScrolling = findGetParameter('horizontalScrolling');
  178. var paramSingleHorizontalStaffline = findGetParameter('singleHorizontalStaffline');
  179. showHeader = (paramShowHeader !== '0');
  180. showControls = false;
  181. if (paramEmbedded) {
  182. showControls = paramShowControls !== '0';
  183. showZoomControl = paramShowZoomControl !== '0';
  184. showPageFormatControl = paramShowPageFormatControl !== '0';
  185. showExportPdfControl = paramShowExportPdfControl !== '0';
  186. }
  187. if (paramZoom) {
  188. if (paramZoom > 0.1 && paramZoom < 5.0) {
  189. zoom = paramZoom;
  190. }
  191. }
  192. if (paramOverflow && typeof paramOverflow === 'string') {
  193. if (paramOverflow === 'hidden' || paramOverflow === 'auto' || paramOverflow === 'scroll' || paramOverflow === 'visible') {
  194. document.body.style.overflow = paramOverflow;
  195. }
  196. }
  197. var compactMode = paramCompactMode && paramCompactMode !== '0';
  198. var measureRangeStart = paramMeasureRangeStart ? Number.parseInt(paramMeasureRangeStart) : 0;
  199. var measureRangeEnd = paramMeasureRangeEnd ? Number.parseInt(paramMeasureRangeEnd) : Number.MAX_SAFE_INTEGER;
  200. if (measureRangeStart && measureRangeEnd && measureRangeEnd < measureRangeStart) {
  201. console.log("[OSMD] warning: measure range end parameter should not be smaller than measure range start. We've set start measure = end measure now.")
  202. measureRangeStart = measureRangeEnd;
  203. }
  204. let pageFormat = paramPageFormat ? paramPageFormat : "Endless";
  205. if (paramPageHeight && paramPageWidth) {
  206. pageFormat = `${paramPageWidth}x${paramPageHeight}`
  207. }
  208. var pageBackgroundColor = paramPageBackgroundColor ? "#" + paramPageBackgroundColor : undefined; // vexflow format, see OSMDOptions. can't use # in parameters.
  209. //console.log("demo: osmd pagebgcolor: " + pageBackgroundColor);
  210. var backendType = (paramBackendType && paramBackendType.toLowerCase) ? paramBackendType : "svg";
  211. var horizontalScrolling = paramHorizontalScrolling === '1';
  212. var singleHorizontalStaffline = paramSingleHorizontalStaffline === '1';
  213. // set the backendSelect debug controls dropdown menu selected item
  214. //console.log("true: " + backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas");
  215. // TODO somehow backendSelect becomes undefined here:
  216. /*if (backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas") {
  217. console.log("here1");
  218. for (var i=0; i<backendSelect.options.length; i++) {
  219. if (backendSelect.options[i].value.toLowerCase() === "canvas") {
  220. backendSelect.selectedIndex = i;
  221. }
  222. }
  223. backendSelect.value = "Canvas";
  224. }*/
  225. divControls = document.getElementById('divControls');
  226. zoomControls = document.getElementById('zoomControls');
  227. header = document.getElementById('header');
  228. err = document.getElementById("error-td");
  229. error_tr = document.getElementById("error-tr");
  230. zoomDivs = [];
  231. zoomDivs.push(document.getElementById("zoom-str"));
  232. zoomDivs.push(document.getElementById("zoom-str-optional"));
  233. custom = document.createElement("option");
  234. selectSample = document.getElementById("selectSample");
  235. selectBounding = document.getElementById("selectBounding");
  236. skylineDebug = document.getElementById("skylineDebug");
  237. bottomlineDebug = document.getElementById("bottomlineDebug");
  238. performanceMode = false;
  239. performanceModeBtn = document.getElementById("performanceMode");
  240. zoomIns = [];
  241. zoomIns.push(document.getElementById("zoom-in-btn"));
  242. zoomIns.push(document.getElementById("zoom-in-btn-optional"));
  243. zoomOuts = [];
  244. zoomOuts.push(document.getElementById("zoom-out-btn"));
  245. zoomOuts.push(document.getElementById("zoom-out-btn-optional"));
  246. canvas = document.createElement("div");
  247. if (horizontalScrolling) {
  248. canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  249. }
  250. //canvas.id = 'osmdCanvasDiv';
  251. //canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  252. previousCursorBtn = document.getElementById("previous-cursor-btn");
  253. nextCursorBtn = document.getElementById("next-cursor-btn");
  254. resetCursorBtn = document.getElementById("reset-cursor-btn");
  255. followCursorCheckbox = document.getElementById("follow-cursor-checkbox");
  256. showCursorBtn = document.getElementById("show-cursor-btn");
  257. hideCursorBtn = document.getElementById("hide-cursor-btn");
  258. backendSelect = document.getElementById("backend-select");
  259. backendSelectDiv = document.getElementById("backend-select-div");
  260. debugReRenderBtn = document.getElementById("debug-re-render-btn");
  261. debugClearBtn = document.getElementById("debug-clear-btn");
  262. selectPageSizes = [];
  263. selectPageSizes.push(document.getElementById("selectPageSize"));
  264. selectPageSizes.push(document.getElementById("selectPageSize-optional"));
  265. printPdfBtns = [];
  266. printPdfBtns.push(document.getElementById("print-pdf-btn"));
  267. printPdfBtns.push(document.getElementById("print-pdf-btn-optional"));
  268. transpose = document.getElementById('transpose');
  269. transposeBtn = document.getElementById('transpose-btn');
  270. playbackControlsButton = document.getElementById("playback-settings-button");
  271. // unmuteButton = document.getElementById("unmute-button");
  272. //var defaultDisplayVisibleValue = "block"; // TODO in some browsers flow could be the better/default value
  273. var defaultVisibilityValue = "visible";
  274. showDebugControls = paramDebugControls !== '0';
  275. if (showDebugControls) {
  276. var elementsToEnable = [
  277. selectSample, selectBounding, selectPageSizes[0], backendSelect, backendSelectDiv, divControls
  278. ];
  279. for (var i=0; i<elementsToEnable.length; i++) {
  280. if (elementsToEnable[i]) { // make sure this element is not null/exists in the index.html, e.g. github.io demo has different index.html
  281. if (elementsToEnable[i].style) {
  282. elementsToEnable[i].style.visibility = defaultVisibilityValue;
  283. elementsToEnable[i].style.opacity = 1.0;
  284. }
  285. }
  286. }
  287. } else {
  288. if (divControls) {
  289. divControls.style.display = "none";
  290. }
  291. }
  292. const optionalControls = document.getElementById('optionalControls');
  293. if (optionalControls) {
  294. if (showControls) {
  295. optionalControls.style.visibility = defaultVisibilityValue;
  296. optionalControls.style.opacity = 0.8;
  297. } else {
  298. optionalControls.style.display = 'none';
  299. }
  300. }
  301. if (!showHeader) {
  302. if (header) {
  303. header.style.display = 'none';
  304. }
  305. } else {
  306. if (header) {
  307. header.style.opacity = 1.0;
  308. }
  309. }
  310. // Hide error
  311. error();
  312. if (showControls) {
  313. const optionalControls = document.getElementById('optionalControls');
  314. if (optionalControls) {
  315. optionalControls.style.opacity = 1.0;
  316. // optionalControls.appendChild(zoomControlsButtons);
  317. // optionalControls.appendChild(zoomControlsString);
  318. optionalControls.style.position = 'absolute';
  319. optionalControls.style.zIndex = '10';
  320. optionalControls.style.right = '10px';
  321. // optionalControls.style.padding = '10px';
  322. }
  323. if (showZoomControl) {
  324. const zoomControlsButtonsColumn = document.getElementById('zoomControlsButtons-optional-column');
  325. zoomControlsButtonsColumn.style.opacity = 1.0;
  326. // const zoomControlsButtons = document.getElementById('zoomControlsButtons-optional');
  327. // zoomControlsButtons.style.opacity = 1.0;
  328. const zoomControlsString = document.getElementById('zoom-str-optional'); // actually === zoomDivs[1] above
  329. if (zoomControlsString) {
  330. zoomControlsString.innerHTML = Math.floor(zoom * 100.0) + "%";
  331. zoomControlsString.style.display = 'inline';
  332. // zoomControlsString.style.padding = '10px';
  333. }
  334. }
  335. if (showExportPdfControl) {
  336. const exportPdfButtonColumn = document.getElementById('print-pdf-btn-optional-column');
  337. if (exportPdfButtonColumn) {
  338. exportPdfButtonColumn.style.opacity = 1.0;
  339. }
  340. }
  341. const pageFormatControlColumn = document.getElementById("selectPageSize-optional-column");
  342. if (pageFormatControlColumn) {
  343. if (showPageFormatControl) {
  344. pageFormatControlColumn.style.opacity = 1.0;
  345. } else {
  346. // showPageFormatControlColumn.innerHTML = "";
  347. // pageFormatControlColumn.style.minWidth = 0;
  348. // pageFormatControlColumn.style.width = 0;
  349. pageFormatControlColumn.style.display = 'none'; // squeezes buttons/columns
  350. // pageFormatControlColumn.style.visibility = 'hidden';
  351. // const optionalControlsColumnContainer = document.getElementById("optionalControlsColumnContainer");
  352. // optionalControlsColumnContainer.removeChild(pageFormatControlColumn);
  353. // optionalControlsColumnContainer.width *= 0.66;
  354. // optionalControls.witdh *= 0.66;
  355. // optionalControls.focus();
  356. }
  357. }
  358. }
  359. // Create select
  360. for (name in samples) {
  361. if (samples.hasOwnProperty(name)) {
  362. option = document.createElement("option");
  363. option.value = samples[name];
  364. option.textContent = name;
  365. }
  366. if (selectSample) {
  367. selectSample.appendChild(option);
  368. }
  369. }
  370. if (selectSample) {
  371. selectSample.onchange = selectSampleOnChange;
  372. }
  373. if (selectBounding) {
  374. selectBounding.onchange = selectBoundingOnChange;
  375. }
  376. for (const selectPageSize of selectPageSizes) {
  377. if (selectPageSize) {
  378. selectPageSize.onchange = function (evt) {
  379. var value = evt.target.value;
  380. openSheetMusicDisplay.setPageFormat(value);
  381. openSheetMusicDisplay.render();
  382. };
  383. }
  384. }
  385. for (const printPdfBtn of printPdfBtns) {
  386. if (printPdfBtn) {
  387. printPdfBtn.onclick = function () {
  388. createPdf();
  389. }
  390. }
  391. }
  392. // Pre-select default music piece
  393. custom.appendChild(document.createTextNode("Custom"));
  394. // Create zoom controls
  395. for (const zoomIn of zoomIns) {
  396. if (zoomIn) {
  397. zoomIn.onclick = function () {
  398. zoom *= 1.2;
  399. scale();
  400. };
  401. }
  402. }
  403. for (const zoomOut of zoomOuts) {
  404. if (zoomOut) {
  405. zoomOut.onclick = function () {
  406. zoom /= 1.2;
  407. scale();
  408. };
  409. }
  410. }
  411. if (skylineDebug) {
  412. skylineDebug.onclick = function () {
  413. openSheetMusicDisplay.DrawSkyLine = !openSheetMusicDisplay.DrawSkyLine;
  414. openSheetMusicDisplay.render();
  415. }
  416. }
  417. if (bottomlineDebug) {
  418. bottomlineDebug.onclick = function () {
  419. openSheetMusicDisplay.DrawBottomLine = !openSheetMusicDisplay.DrawBottomLine;
  420. openSheetMusicDisplay.render();
  421. }
  422. }
  423. if (performanceModeBtn) {
  424. performanceModeBtn.onclick = function () {
  425. performanceMode = !performanceMode;
  426. openSheetMusicDisplay.setOptions({performanceMode});
  427. }
  428. }
  429. if (debugReRenderBtn) {
  430. debugReRenderBtn.onclick = function () {
  431. rerender();
  432. }
  433. }
  434. if (debugClearBtn) {
  435. debugClearBtn.onclick = function () {
  436. openSheetMusicDisplay.clear();
  437. }
  438. }
  439. // Create OSMD object and canvas
  440. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, {
  441. autoResize: true,
  442. backend: backendType,
  443. //backend: "canvas",
  444. //cursorsOptions: [{type: 3, color: "#2bb8cd", alpha: 0.6, follow: true}], // highlight current measure instead of just a small vertical bar over approximate notes
  445. disableCursor: false,
  446. drawingParameters: compactMode ? "compact" : "default", // try compact (instead of default)
  447. drawPartNames: true, // try false
  448. // drawTitle: false,
  449. // drawSubtitle: false,
  450. drawFingerings: true,
  451. //fingeringPosition: "left", // Above/Below is default. try left or right. experimental: above, below.
  452. //fingeringPositionFromXML: false, // do this if you want them always left, for example.
  453. // fingeringInsideStafflines: "true", // default: false. true draws fingerings directly above/below notes
  454. setWantedStemDirectionByXml: true, // try false, which was previously the default behavior
  455. // drawUpToMeasureNumber: 3, // draws only up to measure 3, meaning it draws measure 1 to 3 of the piece.
  456. drawFromMeasureNumber : measureRangeStart,
  457. drawUpToMeasureNumber : measureRangeEnd,
  458. //drawMeasureNumbers: false, // disable drawing measure numbers
  459. //measureNumberInterval: 4, // draw measure numbers only every 4 bars (and at the beginning of a new system)
  460. useXMLMeasureNumbers: true, // read measure numbers from xml
  461. // coloring options
  462. coloringEnabled: true,
  463. // defaultColorNotehead: "#CC0055", // try setting a default color. default is black (undefined)
  464. // defaultColorStem: "#BB0099",
  465. autoBeam: false, // try true, OSMD Function Test AutoBeam sample
  466. autoBeamOptions: {
  467. beam_rests: false,
  468. beam_middle_rests_only: false,
  469. //groups: [[3,4], [1,1]],
  470. maintain_stem_directions: false
  471. },
  472. pageFormat: pageFormat,
  473. pageBackgroundColor: pageBackgroundColor,
  474. renderSingleHorizontalStaffline: singleHorizontalStaffline,
  475. performanceMode: performanceMode
  476. // tupletsBracketed: true, // creates brackets for all tuplets except triplets, even when not set by xml
  477. // tripletsBracketed: true,
  478. // tupletsRatioed: true, // unconventional; renders ratios for tuplets (3:2 instead of 3 for triplets)
  479. });
  480. openSheetMusicDisplay.TransposeCalculator = new TransposeCalculator(); // necessary for using osmd.Sheet.Transpose and osmd.Sheet.Instruments[i].Transpose
  481. //openSheetMusicDisplay.DrawSkyLine = true;
  482. //openSheetMusicDisplay.DrawBottomLine = true;
  483. //openSheetMusicDisplay.setDrawBoundingBox("GraphicalLabel", false);
  484. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to see more detailed control flow information in console
  485. document.body.appendChild(canvas);
  486. window.addEventListener("keydown", function (e) {
  487. var event = window.event ? window.event : e;
  488. // left arrow key
  489. if (event.keyCode === 37) {
  490. openSheetMusicDisplay.cursor.previous();
  491. }
  492. // right arrow key
  493. if (event.keyCode === 39) {
  494. openSheetMusicDisplay.cursor.next();
  495. }
  496. });
  497. previousCursorBtn?.addEventListener("click", function () {
  498. openSheetMusicDisplay.cursor.previous();
  499. });
  500. nextCursorBtn.addEventListener("click", function () {
  501. openSheetMusicDisplay.cursor.next();
  502. });
  503. resetCursorBtn.addEventListener("click", function () {
  504. openSheetMusicDisplay.cursor.reset();
  505. });
  506. if (followCursorCheckbox) {
  507. followCursorCheckbox.onchange = function () {
  508. openSheetMusicDisplay.FollowCursor = !openSheetMusicDisplay.FollowCursor;
  509. }
  510. }
  511. window.addEventListener("wheel", function(e){
  512. if(followCursorCheckbox) {
  513. followCursorCheckbox.checked = false;
  514. openSheetMusicDisplay.FollowCursor = false;
  515. }
  516. });
  517. hideCursorBtn.addEventListener("click", function () {
  518. if (openSheetMusicDisplay.cursor) {
  519. openSheetMusicDisplay.cursor.hide();
  520. } else {
  521. console.info("Can't hide cursor, as it was disabled (e.g. by drawingParameters).");
  522. }
  523. });
  524. showCursorBtn.addEventListener("click", function () {
  525. if (openSheetMusicDisplay.cursor) {
  526. openSheetMusicDisplay.cursor.show();
  527. } else {
  528. console.info("Can't show cursor, as it was disabled (e.g. by drawingParameters).");
  529. }
  530. });
  531. backendSelect.addEventListener("change", function (e) {
  532. var value = e.target.value;
  533. var createNewOsmd = true;
  534. if (createNewOsmd) {
  535. // clears the canvas element
  536. canvas.innerHTML = "";
  537. //openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, { backend: value }); // resets EngravingRules
  538. openSheetMusicDisplay.setOptions({backend: value});
  539. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to get more detailed control flow information
  540. } else {
  541. // alternative, doesn't work yet, see setOptions():
  542. openSheetMusicDisplay.setOptions({ backend: value });
  543. }
  544. console.log("[OSMD] selectSampleOnChange addEventListener change");
  545. // selectSampleOnChange();
  546. });
  547. if(transposeBtn && transpose){
  548. transposeBtn.onclick = function(){
  549. var transposeValue = parseInt(transpose.value);
  550. openSheetMusicDisplay.Sheet.Transpose = transposeValue;
  551. openSheetMusicDisplay.updateGraphic();
  552. rerender();
  553. }
  554. }
  555. playbackControl = demoPlaybackControl(openSheetMusicDisplay);
  556. playbackControlsButton.addEventListener("click", function(){
  557. if(!playbackControl.IsClosed()){
  558. playbackControl.hideControls();
  559. } else {
  560. playbackControl.showControls();
  561. }
  562. });
  563. // TODO after selectSampleOnChange, the resize handler triggers immediately,
  564. // so we render twice at the start of the demo.
  565. // maybe delay the first osmd render, e.g. when window ready?
  566. if (paramOpenUrl) {
  567. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  568. console.log("[OSMD] selectSampleOnChange with " + paramOpenUrl);
  569. }
  570. // DEBUG: cause an error for a certain sample, for testing
  571. // if (paramOpenUrl.startsWith("Beethoven")) {
  572. // paramOpenUrl.causeError();
  573. // }
  574. selectSampleOnChange(paramOpenUrl);
  575. } else {
  576. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  577. console.log("[OSMD] selectSampleOnChange without param");
  578. }
  579. selectSampleOnChange();
  580. }
  581. }
  582. function findGetParameter(parameterName) {
  583. // special treatment for the openUrl parameter, because different systems attach different arguments to an URL.
  584. // because of CORS (cross-origin safety restrictions), you can only load an xml file from the same origin (server).
  585. // test parameter: ?openUrl=https://opensheetmusiceducation.org/index.php?gf-download=2020%2F01%2FJohannSebastianBach_PraeludiumInCDur_BWV846_1.xml&endUrl&form-id=1&field-id=4&hash=c4ba271ef08204a26cbd4cd2d751c53b78f238c25ddbb1f343e1172f2ce2aa53
  586. // (enable the console.log at the end of this method for testing)
  587. // working test parameter in local demo: ?openUrl=OSMD_function_test_all.xml&endUrl
  588. if (parameterName === 'openUrl') {
  589. let startParameterName = 'openUrl=';
  590. let endParameterName = '&endUrl';
  591. let openUrlIndex = location.search.indexOf(startParameterName);
  592. if (openUrlIndex < 0) {
  593. return undefined;
  594. }
  595. let endIndex = location.search.indexOf(endParameterName) + endParameterName.length;
  596. if (endIndex < 0) {
  597. console.log("[OSMD] If using openUrl as a parameter, you have to end it with '&endUrl'. openUrl parameter omitted.");
  598. return undefined;
  599. }
  600. let urlString = location.search.substring(openUrlIndex + startParameterName.length, endIndex - endParameterName.length);
  601. //console.log("openUrl: " + urlString);
  602. return urlString;
  603. }
  604. let result = undefined;
  605. let tmp = [];
  606. location.search
  607. .substr(1)
  608. .split('&')
  609. .forEach(function (item) {
  610. tmp = item.split('=');
  611. if (tmp[0] === parameterName) {
  612. result = decodeURIComponent(tmp[1]);
  613. //console.log('Found param:' + parameterName + ' = ' + result);
  614. }
  615. });
  616. return result;
  617. }
  618. function selectBoundingOnChange(evt) {
  619. var value = evt.target.value;
  620. openSheetMusicDisplay.DrawBoundingBox = value;
  621. }
  622. function selectSampleOnChange(str) {
  623. var comment = undefined;
  624. var sampleStr = undefined;
  625. error();
  626. disable();
  627. var isCustom = typeof str === "string";
  628. if (!isCustom) {
  629. if (selectSample) {
  630. sampleStr = selectSample.value;
  631. str = sampleFolder + sampleStr;
  632. } else {
  633. if (samples && samples.length > 0) {
  634. sampleStr = samples[0];
  635. str = sampleFolder + sampleStr;
  636. } else {
  637. return; // no sample to load right now
  638. }
  639. }
  640. if(comments.hasOwnProperty(sampleStr)){
  641. comment = comments[sampleStr];
  642. }
  643. }
  644. // zoom = 1.0;
  645. setSampleSpecificOptions(str, isCustom);
  646. openSheetMusicDisplay.load(str, comment).then(
  647. function () {
  648. // This gives you access to the osmd object in the console. Do not use in production code
  649. window.osmd = openSheetMusicDisplay;
  650. openSheetMusicDisplay.zoom = zoom;
  651. //openSheetMusicDisplay.Sheet.Transpose = 3; // try transposing between load and first render if you have transpose issues with F# etc
  652. return openSheetMusicDisplay.render(); // comment out this line to test playback without rendering
  653. },
  654. function (e) {
  655. errorLoadingOrRenderingSheet(e, "rendering");
  656. }
  657. ).then(
  658. function () {
  659. return onLoadingEnd(isCustom);
  660. }, function (e) {
  661. errorLoadingOrRenderingSheet(e, "loading");
  662. onLoadingEnd(isCustom);
  663. }
  664. );
  665. }
  666. function setSampleSpecificOptions(str, isCustom) {
  667. if (!isCustom && str.includes("measuresToDraw")) { // set options for measuresToDraw sample
  668. // stash previously set range of measures to draw
  669. if (!measureToDrawRangeNeedsReset) { // only stash once, when measuresToDraw called multiple times in a row
  670. minMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MinMeasureToDrawIndex + 1;
  671. maxMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MaxMeasureToDrawIndex + 1;
  672. }
  673. measureToDrawRangeNeedsReset = true;
  674. // for debugging: draw from a random range of measures
  675. let minMeasureToDraw = Math.ceil(Math.random() * 15); // measures start at 1 (measureIndex = measure number - 1 elsewhere)
  676. let maxMeasureToDraw = Math.ceil(Math.random() * 15);
  677. if (minMeasureToDraw > maxMeasureToDraw) {
  678. minMeasureToDraw = maxMeasureToDraw;
  679. let a = minMeasureToDraw;
  680. maxMeasureToDraw = a;
  681. }
  682. //minMeasureToDraw = 1; // set your custom indexes here. Drawing only one measure can be a special case
  683. //maxMeasureToDraw = 1;
  684. console.log("drawing measures in the range: [" + minMeasureToDraw + "," + maxMeasureToDraw + "]");
  685. openSheetMusicDisplay.setOptions({
  686. drawFromMeasureNumber: minMeasureToDraw,
  687. drawUpToMeasureNumber: maxMeasureToDraw
  688. });
  689. } else if (measureToDrawRangeNeedsReset) { // reset for other samples
  690. openSheetMusicDisplay.setOptions({
  691. drawFromMeasureNumber: minMeasureToDrawStashed,
  692. drawUpToMeasureNumber: maxMeasureToDrawStashed
  693. });
  694. measureToDrawRangeNeedsReset = false;
  695. }
  696. if (!isCustom && str.includes("Test_Container_height")) {
  697. drawingParametersStashed = openSheetMusicDisplay.drawingParameters.drawingParametersEnum;
  698. openSheetMusicDisplay.setOptions({
  699. drawingParameters: "compacttight"
  700. });
  701. drawingParametersNeedsReset = true;
  702. } else if (drawingParametersNeedsReset) {
  703. openSheetMusicDisplay.setOptions({
  704. drawingParameters: drawingParametersStashed
  705. });
  706. drawingParametersNeedsReset = false;
  707. }
  708. // Enable Boomwhacker-like coloring for OSMD Function Test - Auto-Coloring (Boomwhacker-like, custom color set)
  709. if (!isCustom && str.includes("auto-custom-coloring")) { // set options for auto coloring sample
  710. autoCustomColoringOptionNeedsReset = true;
  711. //openSheetMusicDisplay.setOptions({coloringMode: 1}); // Auto-Coloring with pre-defined colors
  712. openSheetMusicDisplay.setOptions({
  713. coloringMode: 2, // custom coloring set. 0 would be XML, 1 autocoloring
  714. coloringSetCustom: ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"],
  715. // last color value of coloringSetCustom is for rest notes
  716. colorStemsLikeNoteheads: true
  717. });
  718. } else if (autoCustomColoringOptionNeedsReset) {
  719. openSheetMusicDisplay.setOptions({ // set default values. better would be to restore to stashed values, but unnecessarily complex for demo
  720. coloringMode: 0,
  721. colorStemsLikeNoteheads: false,
  722. coloringSetCustom: null
  723. });
  724. autoCustomColoringOptionNeedsReset = false;
  725. }
  726. if (!isCustom && str.includes("autobeam")) {
  727. autobeamOptionStashedValue = openSheetMusicDisplay.EngravingRules.AutoBeamNotes; // stash previously set value, to restore later
  728. autobeamOptionNeedsReset = true;
  729. openSheetMusicDisplay.setOptions({ autoBeam: true });
  730. } else if (autobeamOptionNeedsReset) {
  731. openSheetMusicDisplay.setOptions({ autoBeam: autobeamOptionStashedValue });
  732. autobeamOptionNeedsReset = false;
  733. }
  734. if (!isCustom && str.includes("OSMD_Function_Test_System_and_Page_Breaks")) {
  735. pageBreaksOptionStashedValue = openSheetMusicDisplay.EngravingRules.NewPageAtXMLNewPageAttribute;
  736. systemBreaksOptionStashedValue = openSheetMusicDisplay.EngravingRules.NewSystemAtXMLNewSystemAttribute;
  737. pageBreaksOptionNeedsReset = true;
  738. openSheetMusicDisplay.setOptions({ newPageFromXML: true, newSystemFromXML: true });
  739. }
  740. else if (pageBreaksOptionNeedsReset) {
  741. openSheetMusicDisplay.setOptions({ newPageFromXML: pageBreaksOptionStashedValue, newSystemFromXML: systemBreaksOptionStashedValue });
  742. pageBreaksOptionNeedsReset = false;
  743. }
  744. if (!isCustom && str.includes("Schubert_An_die_Musik")) { // TODO weird layout bug here with part names. but shouldn't be in score anyways
  745. drawPartNamesOptionStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartNames;
  746. drawPartAbbreviationsStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartAbbreviations;
  747. openSheetMusicDisplay.setOptions({ drawPartNames: false, drawPartAbbreviations: false }); // TODO sets osmd.drawingParameters.DrawPartNames! also check EngravingRules.RenderPartAbbreviations, was false
  748. drawPartNamesOptionNeedsReset = true;
  749. } else if (drawPartNamesOptionNeedsReset) {
  750. openSheetMusicDisplay.setOptions({ drawPartNames: drawPartNamesOptionStashedValue, drawPartAbbreviations: drawPartAbbreviationsStashedValue });
  751. drawPartNamesOptionNeedsReset = false;
  752. }
  753. }
  754. function errorLoadingOrRenderingSheet(e, loadingOrRenderingString) {
  755. var errorString = "Error " + loadingOrRenderingString + " sheet: " + e;
  756. // Always giving a StackTrace might give us more and better error reports.
  757. // TODO for a release, StackTrace control could be reenabled
  758. errorString += "\n" + "StackTrace: \n" + e.stack;
  759. // }
  760. console.warn(errorString);
  761. }
  762. function onLoadingEnd(isCustom) {
  763. // Remove option from select
  764. if (!isCustom && custom.parentElement === selectSample) {
  765. selectSample.removeChild(custom);
  766. }
  767. if (openSheetMusicDisplay.Sheet) {
  768. playbackControl.initialize();
  769. } else {
  770. console.warn("Sheet couldn't be loaded, so playback control can't be initialized");
  771. }
  772. // Enable controls again
  773. enable();
  774. }
  775. function logCanvasSize() {
  776. for (const zoomDiv of zoomDivs) {
  777. if (zoomDiv) {
  778. zoomDiv.innerHTML = Math.floor(zoom * 100.0) + "%";
  779. }
  780. }
  781. }
  782. function scale() {
  783. disable();
  784. window.setTimeout(function () {
  785. openSheetMusicDisplay.Zoom = zoom;
  786. openSheetMusicDisplay.render();
  787. enable();
  788. }, 0);
  789. }
  790. function rerender() {
  791. disable();
  792. window.setTimeout(function () {
  793. if (openSheetMusicDisplay.IsReadyToRender()) {
  794. openSheetMusicDisplay.render();
  795. } else {
  796. console.log("[OSMD demo] Loses context!"); // TODO not sure that this message is reasonable, renders fine anyways. maybe vexflow context lost?
  797. selectSampleOnChange(); // reload sample e.g. after osmd.clear()
  798. }
  799. enable();
  800. }, 0);
  801. }
  802. function error(errString) {
  803. if (!errString) {
  804. error_tr.style.display = "none";
  805. } else {
  806. console.log("[OSMD demo] error: " + errString)
  807. err.textContent = errString;
  808. error_tr.style.display = "";
  809. canvas.width = canvas.height = 0;
  810. enable();
  811. }
  812. }
  813. // Enable/Disable Controls
  814. function disable() {
  815. document.body.style.opacity = 0.3;
  816. setDisabledForControls("disabled");
  817. }
  818. function enable() {
  819. document.body.style.opacity = 1;
  820. setDisabledForControls("");
  821. logCanvasSize();
  822. }
  823. function setDisabledForControls(disabledValue) {
  824. if (selectSample) {
  825. selectSample.disabled = disabledValue;
  826. }
  827. for (const zoomIn of zoomIns) {
  828. if (zoomIn) {
  829. zoomIn.disabled = disabledValue;
  830. }
  831. }
  832. for (const zoomOut of zoomOuts) {
  833. if (zoomOut) {
  834. zoomOut.disabled = disabledValue;
  835. }
  836. }
  837. }
  838. /**
  839. * Creates a Pdf of the currently rendered MusicXML
  840. * @param pdfName if no name is given, the composer and title of the piece will be used
  841. */
  842. async function createPdf(pdfName) {
  843. if (openSheetMusicDisplay.backendType !== BackendType.SVG) {
  844. console.log("[OSMD] createPdf(): Warning: createPDF is only supported for SVG background for now, not for Canvas." +
  845. " Please use osmd.setOptions({backendType: SVG}).");
  846. return;
  847. }
  848. if (pdfName === undefined) {
  849. pdfName = openSheetMusicDisplay.sheet.FullNameString + ".pdf";
  850. }
  851. const backends = openSheetMusicDisplay.drawer.Backends;
  852. let svgElement = backends[0].getSvgElement();
  853. let pageWidth = 210;
  854. let pageHeight = 297;
  855. const engravingRulesPageFormat = openSheetMusicDisplay.rules.PageFormat;
  856. if (engravingRulesPageFormat && !engravingRulesPageFormat.IsUndefined) {
  857. pageWidth = engravingRulesPageFormat.width;
  858. pageHeight = engravingRulesPageFormat.height;
  859. } else {
  860. pageHeight = pageWidth * svgElement.clientHeight / svgElement.clientWidth;
  861. }
  862. const orientation = pageHeight > pageWidth ? "p" : "l";
  863. // create a new jsPDF instance
  864. const pdf = new jsPDF.jsPDF({
  865. orientation: orientation,
  866. unit: "mm",
  867. format: [pageWidth, pageHeight]
  868. });
  869. //const scale = pageWidth / svgElement.clientWidth;
  870. for (let idx = 0, len = backends.length; idx < len; ++idx) {
  871. if (idx > 0) {
  872. pdf.addPage();
  873. }
  874. svgElement = backends[idx].getSvgElement();
  875. if (!pdf.svg && !svg2pdf) { // this line also serves to make the svg2pdf not unused, though it's still necessary
  876. // we need svg2pdf to have pdf.svg defined
  877. console.log("svg2pdf missing, necessary for jspdf.svg().");
  878. return;
  879. }
  880. await pdf.svg(svgElement, {
  881. x: 0,
  882. y: 0,
  883. width: pageWidth,
  884. height: pageHeight,
  885. })
  886. }
  887. pdf.save(pdfName); // save/download the created pdf
  888. //pdf.output("pdfobjectnewwindow", {filename: "osmd_createPDF.pdf"}); // open PDF in new tab/window
  889. // note that using jspdf with svg2pdf creates unnecessary console warnings "AcroForm-Classes are not populated into global-namespace..."
  890. // this will hopefully be fixed with a new jspdf release, see https://github.com/yWorks/jsPDF/pull/32
  891. }
  892. var demoPlaybackControl = function(osmd) {
  893. var playbackListener = {
  894. play() {
  895. followCursorCheckbox.checked = true;
  896. openSheetMusicDisplay.FollowCursor = true;
  897. },
  898. pause() {},
  899. reset() {},
  900. bpmChanged() {},
  901. volumeChanged() {},
  902. volumeMute() {},
  903. volumeUnmute() {}
  904. }
  905. var timingSource = new LinearTimingSource();
  906. var playbackManager = new PlaybackManager(timingSource, undefined, new BasicAudioPlayer(), undefined);
  907. playbackManager.DoPlayback = true;
  908. playbackManager.DoPreCount = false;
  909. playbackManager.PreCountMeasures = 1; // note that DoPreCount has to be true for a precount to happen
  910. var playbackControlPanel = new ControlPanel();
  911. playbackControlPanel.addListener(playbackManager);
  912. playbackControlPanel.addListener(playbackListener);
  913. function initialize() {
  914. timingSource.reset();
  915. timingSource.pause();
  916. timingSource.Settings = osmd.Sheet.playbackSettings;
  917. playbackManager.initialize(osmd.Sheet.musicPartManager);
  918. //playbackManager.removeListener(osmd.cursor); // only necessary if no duplicate checks in addListener
  919. playbackManager.addListener(osmd.cursor);
  920. playbackManager.addListener(playbackControlPanel);
  921. playbackManager.reset();
  922. osmd.PlaybackManager = playbackManager;
  923. playbackControlPanel.clearVolumeTracks();
  924. playbackControlPanel.addVolumeTrack(playbackManager.Metronome.Name, playbackManager.Metronome.Id, playbackManager.Metronome.Volume*100);
  925. for(const instrId of playbackManager.InstrumentIdMapping.keys()) {
  926. const instr = playbackManager.InstrumentIdMapping.getValue(instrId);
  927. playbackControlPanel.addVolumeTrack(instr.Name, instrId, instr.Volume * 100);
  928. }
  929. playbackControlPanel.bpmChanged(osmd.Sheet.DefaultStartTempoInBpm);
  930. }
  931. function showControls() {
  932. playbackControlPanel.show();
  933. }
  934. function hideControls() {
  935. playbackControlPanel.hideAndClear();
  936. }
  937. function IsClosed() {
  938. return playbackControlPanel.IsClosed;
  939. }
  940. return {
  941. initialize: initialize,
  942. showControls: showControls,
  943. hideControls: hideControls,
  944. IsClosed: IsClosed
  945. }
  946. };
  947. // Register events: load, drag&drop
  948. window.addEventListener("load", function () {
  949. init();
  950. });
  951. window.addEventListener("dragenter", function (event) {
  952. event.preventDefault();
  953. disable();
  954. });
  955. window.addEventListener("dragover", function (event) {
  956. event.preventDefault();
  957. });
  958. window.addEventListener("dragleave", function (event) {
  959. enable();
  960. });
  961. window.addEventListener("drop", function (event) {
  962. event.preventDefault();
  963. if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {
  964. return;
  965. }
  966. // Add "Custom..." score
  967. selectSample.appendChild(custom);
  968. custom.selected = "selected";
  969. // Read dragged file
  970. var reader = new FileReader();
  971. reader.onload = function (res) {
  972. selectSampleOnChange(res.target.result);
  973. };
  974. var filename = event.dataTransfer.files[0].name;
  975. if (filename.toLowerCase().indexOf(".xml") > 0
  976. || filename.toLowerCase().indexOf(".musicxml") > 0) {
  977. reader.readAsText(event.dataTransfer.files[0]);
  978. } else if (event.dataTransfer.files[0].name.toLowerCase().indexOf(".mxl") > 0) {
  979. reader.readAsBinaryString(event.dataTransfer.files[0]);
  980. }
  981. else {
  982. alert("No vaild .xml/.mxl/.musicxml file!");
  983. }
  984. });
  985. }());