-
Notifications
You must be signed in to change notification settings - Fork 285
Expand file tree
/
Copy pathAlphaTabApiBase.ts
More file actions
4341 lines (4111 loc) · 143 KB
/
Copy pathAlphaTabApiBase.ts
File metadata and controls
4341 lines (4111 loc) · 143 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AlphaTabError, AlphaTabErrorType } from '@coderline/alphatab/AlphaTabError';
import type { CoreSettings } from '@coderline/alphatab/CoreSettings';
import { Environment } from '@coderline/alphatab/Environment';
import {
EventEmitter,
EventEmitterOfT,
type IEventEmitter,
type IEventEmitterOfT
} from '@coderline/alphatab/EventEmitter';
import { AlphaTexImporter } from '@coderline/alphatab/importer/AlphaTexImporter';
import { Logger } from '@coderline/alphatab/Logger';
import { AlphaSynthMidiFileHandler } from '@coderline/alphatab/midi/AlphaSynthMidiFileHandler';
import type { BeatTickLookupItem, IBeatVisibilityChecker } from '@coderline/alphatab/midi/BeatTickLookup';
import type {
MetaDataEvent,
MetaEvent,
MetaNumberEvent,
Midi20PerNotePitchBendEvent,
SystemCommonEvent,
SystemExclusiveEvent
} from '@coderline/alphatab/midi/DeprecatedEvents';
import type {
AlphaTabMetronomeEvent,
AlphaTabRestEvent,
ControlChangeEvent,
EndOfTrackEvent,
MidiEvent,
MidiEventType,
NoteBendEvent,
NoteOffEvent,
NoteOnEvent,
PitchBendEvent,
ProgramChangeEvent,
TempoChangeEvent,
TimeSignatureEvent
} from '@coderline/alphatab/midi/MidiEvent';
import { MidiFile } from '@coderline/alphatab/midi/MidiFile';
import { MidiFileGenerator } from '@coderline/alphatab/midi/MidiFileGenerator';
import {
type MidiTickLookup,
type MidiTickLookupFindBeatResult,
MidiTickLookupFindBeatResultCursorMode
} from '@coderline/alphatab/midi/MidiTickLookup';
import type { Beat } from '@coderline/alphatab/model/Beat';
import { ModelUtils } from '@coderline/alphatab/model/ModelUtils';
import type { Note } from '@coderline/alphatab/model/Note';
import type { Score } from '@coderline/alphatab/model/Score';
import type { Track } from '@coderline/alphatab/model/Track';
import { PlayerMode, ScrollMode } from '@coderline/alphatab/PlayerSettings';
import type { IContainer } from '@coderline/alphatab/platform/IContainer';
import type { IMouseEventArgs } from '@coderline/alphatab/platform/IMouseEventArgs';
import type { IUiFacade } from '@coderline/alphatab/platform/IUiFacade';
import { ResizeEventArgs } from '@coderline/alphatab/ResizeEventArgs';
import { BeatContainerGlyph } from '@coderline/alphatab/rendering/glyphs/BeatContainerGlyph';
import type { IScoreRenderer } from '@coderline/alphatab/rendering/IScoreRenderer';
import type { RenderFinishedEventArgs } from '@coderline/alphatab/rendering/RenderFinishedEventArgs';
import { ScoreRenderer } from '@coderline/alphatab/rendering/ScoreRenderer';
import { ScoreRendererWrapper } from '@coderline/alphatab/rendering/ScoreRendererWrapper';
import type { BeatBounds } from '@coderline/alphatab/rendering/utils/BeatBounds';
import { Bounds } from '@coderline/alphatab/rendering/utils/Bounds';
import type { BoundsLookup } from '@coderline/alphatab/rendering/utils/BoundsLookup';
import type { MasterBarBounds } from '@coderline/alphatab/rendering/utils/MasterBarBounds';
import type { StaffSystemBounds } from '@coderline/alphatab/rendering/utils/StaffSystemBounds';
import {
HorizontalContinuousScrollHandler,
HorizontalOffScreenScrollHandler,
HorizontalSmoothScrollHandler,
type IScrollHandler,
VerticalContinuousScrollHandler,
VerticalOffScreenScrollHandler,
VerticalSmoothScrollHandler
} from '@coderline/alphatab/ScrollHandlers';
import type { Settings } from '@coderline/alphatab/Settings';
import { ActiveBeatsChangedEventArgs } from '@coderline/alphatab/synth/ActiveBeatsChangedEventArgs';
import { AlphaSynthWrapper } from '@coderline/alphatab/synth/AlphaSynthWrapper';
import { ExternalMediaPlayer } from '@coderline/alphatab/synth/ExternalMediaPlayer';
import type { IAlphaSynth } from '@coderline/alphatab/synth/IAlphaSynth';
import {
AudioExportOptions,
type IAudioExporter,
type IAudioExporterWorker
} from '@coderline/alphatab/synth/IAudioExporter';
import type { ISynthOutputDevice } from '@coderline/alphatab/synth/ISynthOutput';
import type { MidiEventsPlayedEventArgs } from '@coderline/alphatab/synth/MidiEventsPlayedEventArgs';
import { PlaybackRange } from '@coderline/alphatab/synth/PlaybackRange';
import type { PlaybackRangeChangedEventArgs } from '@coderline/alphatab/synth/PlaybackRangeChangedEventArgs';
import { PlayerState } from '@coderline/alphatab/synth/PlayerState';
import type { PlayerStateChangedEventArgs } from '@coderline/alphatab/synth/PlayerStateChangedEventArgs';
import type { PositionChangedEventArgs } from '@coderline/alphatab/synth/PositionChangedEventArgs';
/**
* @internal
* @record
*/
interface SelectionInfo {
beat: Beat;
bounds?: BeatBounds;
}
/**
* Holds information about the highlights shown for the playback range.
* @public
* @record
*/
export interface PlaybackHighlightChangeEventArgs {
/**
* The beat where the selection starts. undefined if there is no selection.
*/
startBeat?: Beat;
/**
* The bounds of the start beat to determine its location and size.
*/
startBeatBounds?: BeatBounds;
/**
* The beat where the selection ends. undefined if there is no selection.
*/
endBeat?: Beat;
/**
* The bounds of the end beat to determine its location and size.
*/
endBeatBounds?: BeatBounds;
/**
* A list of the individual rectangular areas where highlight blocks are placed.
* If a selection spans multiple lines this array will hold all items.
*/
highlightBlocks?: Bounds[];
}
/**
* @internal
*/
class BoundsLookupVisibilityChecker implements IBeatVisibilityChecker {
public bounds: BoundsLookup | null = null;
public isVisible(beat: Beat): boolean {
const bounds = this.bounds;
if (!bounds) {
return false;
}
return bounds.findBeat(beat) !== null;
}
}
/**
* This class represents the public API of alphaTab and provides all logic to display
* a music sheet in any UI using the given {@link IUiFacade}
* @param <TSettings> The UI object holding the settings.
* @public
*/
export class AlphaTabApiBase<TSettings> {
private _startTime: number = 0;
private _trackIndexes: number[] | null = null;
private _trackIndexLookup: Set<number> | null = null;
private readonly _beatVisibilityChecker = new BoundsLookupVisibilityChecker();
private _isDestroyed: boolean = false;
private _score: Score | null = null;
private _tracks: Track[] = [];
private _actualPlayerMode: PlayerMode = PlayerMode.Disabled;
private _player!: AlphaSynthWrapper;
private _renderer: ScoreRendererWrapper;
private _defaultScrollHandler?: IScrollHandler;
/**
* An indicator by how many midi-ticks the song contents are shifted.
* Grace beats at start might require a shift for the first beat to start at 0.
* This information can be used to translate back the player time axis to the music notation.
*/
public get midiTickShift() {
return this._player.midiTickShift;
}
/**
* The actual player mode which is currently active.
* @remarks
* Allows determining whether a backing track or the synthesizer is active in case automatic detection is enabled.
* @category Properties - Player
* @since 1.6.0
*/
public get actualPlayerMode(): PlayerMode {
return this._actualPlayerMode;
}
/**
* The UI facade used for interacting with the user interface (like the browser).
* @remarks
* The implementation depends on the platform alphaTab is running in (e.g. the web version in the browser, WPF in .net etc.)
* @category Properties - Core
* @since 0.9.4
*/
public readonly uiFacade: IUiFacade<TSettings>;
/**
* The UI container that holds the whole alphaTab control.
* @remarks
* Gets the UI container that represents the element on which alphaTab was initialized. Note that this is not the raw instance, but a UI framework specific wrapper for alphaTab.
* @category Properties - Core
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* const container = api.container;
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* var container = api.Container;
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* val container = api.container;
* ```
*/
public readonly container: IContainer;
/**
* The score renderer used for rendering the music sheet.
* @remarks
* This is the low-level API responsible for the actual rendering engine.
* Gets access to the underling {@link IScoreRenderer} that is used for the rendering.
*
* @category Properties - Core
* @since 0.9.4
*/
public get renderer(): IScoreRenderer {
return this._renderer;
}
/**
* The score holding all information about the song being rendered
* @category Properties - Core
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* updateScoreInfo(api.score);
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* UpdateScoreInfo(api.Score);
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* updateScoreInfo(api.score)
* ```
*/
public get score(): Score | null {
return this._score;
}
/**
* The settings that are used for rendering the music notation.
* @remarks
* Gets access to the underling {@link Settings} object that is currently used by alphaTab.
*
* @category Properties - Core
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* showSettingsModal(api.settings);
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* ShowSettingsDialog(api.Settings);
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* showSettingsDialog(api.settings)
* ```
*/
public settings!: Settings;
/**
* The list of the tracks that are currently rendered.
*
* @category Properties - Core
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* highlightCurrentTracksInTrackSelector(api.tracks);
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* HighlightCurrentTracksInTrackSelector(api.Tracks);
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* highlightCurrentTracksInTrackSelector(api.tracks)
* ```
*/
public get tracks(): Track[] {
return this._tracks;
}
/**
* The UI container that will hold all rendered results.
* @since 0.9.4
* @category Properties - Core
*/
public readonly canvasElement: IContainer;
/**
* Initializes a new instance of the {@link AlphaTabApiBase} class.
* @param uiFacade The UI facade to use for interacting with the user interface.
* @param settings The UI settings object to use for loading the settings.
*/
public constructor(uiFacade: IUiFacade<TSettings>, settings: TSettings) {
this.uiFacade = uiFacade;
this.container = uiFacade.rootContainer;
this.activeBeatsChanged = new EventEmitterOfT<ActiveBeatsChangedEventArgs>(() => {
if (this._player.state === PlayerState.Playing && this._currentBeat) {
return new ActiveBeatsChangedEventArgs(this._currentBeat!.beatLookup.highlightedBeats.map(h => h.beat));
}
return null;
});
this.playedBeatChanged = new EventEmitterOfT<Beat>(() => {
if (this._player.state === PlayerState.Playing && this._currentBeat) {
return this._currentBeat.beat;
}
return null;
});
this.scoreLoaded = new EventEmitterOfT<Score>(() => {
if (this._score) {
return this._score;
}
return null;
});
this.midiLoaded = new EventEmitterOfT<PositionChangedEventArgs>(() => {
return this._player.loadedMidiInfo ?? null;
});
uiFacade.initialize(this, settings);
Logger.logLevel = this.settings.core.logLevel;
this.settings.handleBackwardsCompatibility();
Environment.printEnvironmentInfo(false);
this.canvasElement = uiFacade.createCanvasElement();
this.container.appendChild(this.canvasElement);
this._renderer = new ScoreRendererWrapper();
if (
this.settings.core.useWorkers &&
this.uiFacade.areWorkersSupported &&
Environment.getRenderEngineFactory(this.settings.core.engine).supportsWorkers
) {
this._renderer.instance = this.uiFacade.createWorkerRenderer();
} else {
this._renderer.instance = new ScoreRenderer(this.settings);
}
this.container.resize.on(
Environment.throttle(() => {
if (this._isDestroyed) {
return;
}
if (this.container.width !== this._renderer.width) {
this.triggerResize();
}
}, uiFacade.resizeThrottle)
);
const initialResizeEventInfo: ResizeEventArgs = new ResizeEventArgs();
initialResizeEventInfo.oldWidth = this._renderer.width;
initialResizeEventInfo.newWidth = this.container.width | 0;
initialResizeEventInfo.settings = this.settings;
this._onResize(initialResizeEventInfo);
this._renderer.preRender.on(this._onRenderStarted.bind(this));
this._renderer.renderFinished.on(renderingResult => {
this._onRenderFinished(renderingResult);
});
this._renderer.postRenderFinished.on(() => {
const duration: number = Date.now() - this._startTime;
Logger.debug('rendering', `Rendering completed in ${duration}ms`);
this._onPostRenderFinished();
});
this._renderer.preRender.on(_ => {
this._startTime = Date.now();
});
this._renderer.partialLayoutFinished.on(r => this._appendRenderResult(r, false));
this._renderer.partialRenderFinished.on(this._updateRenderResult.bind(this));
this._renderer.renderFinished.on(r => {
this._appendRenderResult(r, true);
});
this._renderer.error.on(this.onError.bind(this));
this._setupPlayerWrapper();
if (this.settings.player.playerMode !== PlayerMode.Disabled) {
this._setupOrDestroyPlayer();
}
this._setupClickHandling();
// delay rendering to allow ui to hook up with events first.
this.uiFacade.beginInvoke(() => {
this.uiFacade.initialRender();
});
}
private _setupPlayerWrapper() {
const player = new AlphaSynthWrapper();
this._player = player;
player.ready.on(() => {
this.loadMidiForScore();
});
player.readyForPlayback.on(() => {
this._onPlayerReady();
if (this.tracks) {
for (const track of this.tracks) {
const volume: number = track.playbackInfo.volume / 16;
player.setChannelVolume(track.playbackInfo.primaryChannel, volume);
player.setChannelVolume(track.playbackInfo.secondaryChannel, volume);
}
}
});
player.soundFontLoaded.on(this._onSoundFontLoaded.bind(this));
player.soundFontLoadFailed.on(e => {
this.onError(e);
});
player.midiLoaded.on(this._onMidiLoaded.bind(this));
player.midiLoadFailed.on(e => {
this.onError(e);
});
player.stateChanged.on(this._onPlayerStateChanged.bind(this));
player.positionChanged.on(this._onPlayerPositionChanged.bind(this));
player.midiEventsPlayed.on(this._onMidiEventsPlayed.bind(this));
player.playbackRangeChanged.on(this._onPlaybackRangeChanged.bind(this));
player.finished.on(this._onPlayerFinished.bind(this));
}
/**
* Destroys the alphaTab control and restores the initial state of the UI.
* @remarks
* This function destroys the alphaTab control and tries to restore the initial state of the UI. This might be useful if
* our website is quite dynamic and you need to uninitialize alphaTab from an element again. After destroying alphaTab
* it cannot be used anymore. Any further usage leads to unexpected behavior.
*
* @category Methods - Core
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.destroy();
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* api.Destroy();
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* api.destroy()
* ```
*/
public destroy(): void {
this._isDestroyed = true;
this._player.destroy();
this.uiFacade.destroy();
this._renderer.destroy();
}
/**
* Applies any changes that were done to the settings object.
* @remarks
* It also informs the {@link renderer} about any new values to consider.
* By default alphaTab will not trigger any re-rendering or settings update just if the settings object itself was changed. This method must be called
* to trigger an update of the settings in all components. Then a re-rendering can be initiated using the {@link render} method.
*
* @category Methods - Core
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.settings.display.scale = 2.0;
* api.updateSettings();
* api.render();
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
*
* api.Settings.Display.Scale = 2.0;
* api.UpdateSettings();
* api.Render()
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
*
* api.settings.display.scale = 2.0
* api.updateSettings()
* api.render()
* ```
*/
public updateSettings(): void {
this.settings.handleBackwardsCompatibility();
const score = this.score;
if (score) {
ModelUtils.applyPitchOffsets(this.settings, score);
}
this._updateRenderer();
this._renderer.updateSettings(this.settings);
this._setupOrDestroyPlayer();
this._onSettingsUpdated();
}
private _updateRenderer() {
const renderer = this._renderer;
if (
this.settings.core.useWorkers &&
this.uiFacade.areWorkersSupported &&
Environment.getRenderEngineFactory(this.settings.core.engine).supportsWorkers
) {
// switch from non-worker to worker renderer
if (renderer.instance instanceof ScoreRenderer) {
renderer.destroy();
renderer.instance = this.uiFacade.createWorkerRenderer();
}
} else {
// switch from worker to non-worker renderer
if (!(renderer.instance instanceof ScoreRenderer)) {
renderer.destroy();
renderer.instance = new ScoreRenderer(this.settings);
}
}
}
/**
* Initiates a load of the score using the given data.
* @returns true if the data object is supported and a load was initiated, otherwise false
* @param scoreData The data container supported by {@link IUiFacade}. The supported types is depending on the platform:
*
* * A `alphaTab.model.Score` instance (all platforms)
* * A `ArrayBuffer` or `Uint8Array` containing one of the supported file formats (all platforms, native byte array or input streams on other platforms)
* * A url from where to download the binary data of one of the supported file formats (browser only)
*
* @param trackIndexes The indexes of the tracks from the song that should be rendered. If not provided, the first track of the
* song will be shown.
* @category Methods - Player
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.load('/assets/MyFile.gp');
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* api.Load(System.IO.File.OpenRead("MyFile.gp"));
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* contentResolver.openInputStream(uri).use {
* api.load(it)
* }
* ```
*/
public load(scoreData: unknown, trackIndexes?: number[]): boolean {
try {
return this.uiFacade.load(
scoreData,
score => {
this.renderScore(score, trackIndexes);
},
error => {
this.onError(error);
}
);
} catch (e) {
this.onError(e as Error);
return false;
}
}
/**
* Initiates a rendering of the given score.
* @param score The score containing the tracks to be rendered.
* @param trackIndexes The indexes of the tracks from the song that should be rendered. If not provided, the first track of the
* song will be shown.
*
* @category Methods - Core
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.RenderScore(generateScore(),[ 2, 3 ]);
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* api.RenderScore(GenerateScore(), new double[] { 2, 3 });
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* api.renderScore(generateScore(), alphaTab.collections.DoubleList(2, 3));
* ```
*/
public renderScore(score: Score, trackIndexes?: number[]): void {
const tracks: Track[] = [];
if (!trackIndexes) {
if (score.tracks.length > 0) {
tracks.push(score.tracks[0]);
}
} else {
if (trackIndexes.length === 0) {
if (score.tracks.length > 0) {
tracks.push(score.tracks[0]);
}
} else if (trackIndexes.length === 1 && trackIndexes[0] === -1) {
for (const track of score.tracks) {
tracks.push(track);
}
} else {
for (const index of trackIndexes) {
if (index >= 0 && index <= score.tracks.length) {
tracks.push(score.tracks[index]);
}
}
}
}
this._internalRenderTracks(score, tracks);
}
/**
* Renders the given list of tracks.
* @param tracks The tracks to render. They must all belong to the same score.
*
* @category Methods - Core
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.renderTracks([api.score.tracks[0], api.score.tracks[1]]);
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* api.RenderTracks(new []{
* api.Score.Tracks[2],
* api.Score.Tracks[3]
* });
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* api.renderTracks(alphaTab.collections.List(
* api.score.tracks[2],
* api.score.tracks[3]
* }
* ```
*/
public renderTracks(tracks: Track[]): void {
if (tracks.length > 0) {
const score: Score = tracks[0].score;
for (const track of tracks) {
if (track.score !== score) {
this.onError(
new AlphaTabError(
AlphaTabErrorType.General,
'All rendered tracks must belong to the same score.'
)
);
return;
}
}
this._internalRenderTracks(score, tracks);
}
}
private _internalRenderTracks(score: Score, tracks: Track[]): void {
ModelUtils.applyPitchOffsets(this.settings, score);
if (score !== this.score) {
this._score = score;
this._tracks = tracks;
this._tickCache = null;
this._trackIndexes = [];
for (const track of tracks) {
this._trackIndexes.push(track.index);
}
this._trackIndexLookup = new Set<number>(this._trackIndexes);
this._onScoreLoaded(score);
this.loadMidiForScore();
this.render();
} else {
this._tracks = tracks;
const startIndex = ModelUtils.computeFirstDisplayedBarIndex(score, this.settings);
const endIndex = ModelUtils.computeLastDisplayedBarIndex(score, this.settings, startIndex);
if (this._tickCache) {
this._tickCache.multiBarRestInfo = ModelUtils.buildMultiBarRestInfo(this.tracks, startIndex, endIndex);
}
this._trackIndexes = [];
for (const track of tracks) {
this._trackIndexes.push(track.index);
}
this._trackIndexLookup = new Set<number>(this._trackIndexes);
this.render();
}
}
/**
* @internal
*/
public triggerResize(): void {
if (!this.container.isVisible) {
Logger.warning(
'Rendering',
'AlphaTab container was invisible while autosizing, waiting for element to become visible',
null
);
this.uiFacade.rootContainerBecameVisible.on(() => {
Logger.debug('Rendering', 'AlphaTab container became visible, doing autosizing', null);
this.triggerResize();
});
} else {
const resizeEventInfo: ResizeEventArgs = new ResizeEventArgs();
resizeEventInfo.oldWidth = this._renderer.width;
resizeEventInfo.newWidth = this.container.width;
resizeEventInfo.settings = this.settings;
this._onResize(resizeEventInfo);
this._renderer.updateSettings(this.settings);
this._renderer.width = this.container.width;
this._renderer.resizeRender();
}
}
private _appendRenderResult(result: RenderFinishedEventArgs, isLast: boolean): void {
// resizing the canvas and wrapper elements at the end is enough
// it avoids flickering on resizes and re-renders.
// the individual partials are anyhow sized correctly
if (isLast) {
this.canvasElement.width = result.totalWidth;
this.canvasElement.height = result.totalHeight;
if (this._cursorWrapper) {
this._cursorWrapper.width = result.totalWidth;
this._cursorWrapper.height = result.totalHeight;
}
}
if (result.width > 0 || result.height > 0) {
this.uiFacade.beginAppendRenderResults(result);
}
if (isLast) {
this.uiFacade.beginAppendRenderResults(null);
}
}
private _updateRenderResult(result: RenderFinishedEventArgs | null): void {
if (result && result.renderResult) {
this.uiFacade.beginUpdateRenderResults(result);
}
}
/**
* Tells alphaTab to render the given alphaTex.
* @param tex The alphaTex code to render.
* @param tracks If set, the given tracks will be rendered, otherwise the first track only will be rendered.
* @category Methods - Core
* @since 0.9.4
*
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.tex("\\title 'Test' . 3.3.4");
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* api.Tex("\\title 'Test' . 3.3.4");
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* api.tex("\\title 'Test' . 3.3.4");
* ```
*/
public tex(tex: string, tracks?: number[]): void {
try {
const parser = new AlphaTexImporter();
parser.logErrors = true;
parser.initFromString(tex, this.settings);
const score: Score = parser.readScore();
this.renderScore(score, tracks);
} catch (e) {
this.onError(e as Error);
}
}
/**
* Triggers a load of the soundfont from the given data.
* @remarks
* AlphaTab only supports SoundFont2 and SoundFont3 {@since 1.4.0} encoded soundfonts for loading. To load a soundfont the player must be enabled in advance.
*
* @param data The data object to decode. The supported data types is depending on the platform.
*
* * A `ArrayBuffer` or `Uint8Array` (all platforms, native byte array or input streams on other platforms)
* * A url from where to download the binary data of one of the supported file formats (browser only)
*
* @param append Whether to fully replace or append the data from the given soundfont.
* @returns `true` if the passed in object is a supported format and loading was initiated, otherwise `false`.
*
* @category Methods - Player
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.loadSoundFont('/assets/MyFile.sf2');
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* api.LoadSoundFont(System.IO.File.OpenRead("MyFile.sf2"));
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* contentResolver.openInputStream(uri).use {
* api.loadSoundFont(it)
* }
* ```
*/
public loadSoundFont(data: unknown, append: boolean = false): boolean {
return this.uiFacade.loadSoundFont(data, append);
}
/**
* Unloads all presets from previously loaded SoundFonts.
* @remarks
* This function resets the player internally to not have any SoundFont loaded anymore. This allows you to reduce the memory usage of the page
* if multiple partial SoundFonts are loaded via `loadSoundFont(..., true)`. Depending on the workflow you might also just want to use `loadSoundFont(..., false)` once
* instead of unloading the previous SoundFonts.
*
* @category Methods - Player
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.loadSoundFont('/assets/guitars.sf2', true);
* api.loadSoundFont('/assets/pianos.sf2', true);
* // ..
* api.resetSoundFonts();
* api.loadSoundFont('/assets/synths.sf2', true);
* ```
*
* @example
* C#
* ```cs
*var api = new AlphaTabApi<MyControl>(...);
*api.LoadSoundFont(System.IO.File.OpenRead("guitars.sf2"), true);
*api.LoadSoundFont(System.IO.File.OpenRead("pianos.sf2"), true);
*...
*api.ResetSoundFonts();
*api.LoadSoundFont(System.IO.File.OpenRead("synths.sf2"), true);
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* api.loadSoundFont(readResource("guitars.sf2"), true)
* api.loadSoundFont(readResource("pianos.sf2"), true)
* ...
* api.resetSoundFonts()
* api.loadSoundFont(readResource("synths.sf2"), true)
* ```
*/
public resetSoundFonts(): void {
this._player.resetSoundFonts();
}
/**
* Initiates a re-rendering of the current setup.
* @remarks
* If rendering is not yet possible, it will be deferred until the UI changes to be ready for rendering.
*
* @category Methods - Core
* @since 0.9.4
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.render();
* ```
*
* @example
* C#
* ```cs
* var api = new AlphaTabApi<MyControl>(...);
* api.Render();
* ```
*
* @example
* Android
* ```kotlin
* val api = AlphaTabApi<MyControl>(...)
* api.render()
* ```
*/
public render(): void {
if (this.uiFacade.canRender) {
// when font is finally loaded, start rendering
this._renderer.width = this.container.width;
this._renderer.renderScore(this.score, this._trackIndexes);
} else {
this.uiFacade.canRenderChanged.on(() => this.render());
}
}
private _tickCache: MidiTickLookup | null = null;
/**
* A custom scroll handler which will be used to handle scrolling operations during playback.
*
* @category Properties - Player
* @since 1.8.0
* @example
* JavaScript
* ```js
* const api = new alphaTab.AlphaTabApi(document.querySelector('#alphaTab'));
* api.customScrollHandler = {
* forceScrollTo(currentBeatBounds) {