index.js 49 KB

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