PlaybackManager.ts 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. import { ITimingSource } from "../Common/Interfaces/ITimingSource";
  2. import { IMessageViewer } from "../Common/Interfaces/IMessageViewer";
  3. import { IAudioPlayer } from "../Common/Interfaces/IAudioPlayer";
  4. import { MusicPartManager, MusicPartManagerIterator } from "../MusicalScore/MusicParts";
  5. import { PlaybackIterator } from "../MusicalScore/Playback/PlaybackIterator";
  6. import { Dictionary } from "typescript-collections";
  7. import { Staff, SourceMeasure, VoiceEntry, Note, MidiInstrument } from "../MusicalScore/VoiceData";
  8. import { Fraction } from "../Common/DataObjects";
  9. import { MetronomeInstrument } from "./MetronomeInstrument";
  10. import { CursorPosChangedData } from "../Common/DataObjects/CursorPosChangedData";
  11. import { Repetition } from "../MusicalScore/MusicSource";
  12. import { TextTranslation } from "../Common/Strings/TextTranslation";
  13. import { NoteState, Instrument, SubInstrument, MusicSheet } from "../MusicalScore";
  14. import { DynamicsContainer } from "../MusicalScore/VoiceData/HelperObjects";
  15. import { PlaybackEntry } from "../MusicalScore/Playback/PlaybackEntry";
  16. import { ContinuousDynamicExpression } from "../MusicalScore/VoiceData/Expressions/ContinuousExpressions";
  17. import { PlaybackNote } from "../MusicalScore/Playback/PlaybackNote";
  18. import log from "loglevel";
  19. import { IAudioMetronomePlayer } from "../Common/Interfaces/IAudioMetronomePlayer";
  20. import { ISettableInstrument } from "../Common/Interfaces/ISettableInstrument";
  21. import { PlaybackState, MessageBoxType } from "../Common/Enums/PsEnums";
  22. import { IPlaybackListener } from "../Common/Interfaces/IPlaybackListener";
  23. import { IPlaybackParametersListener } from "../Common/Interfaces/IPlaybackParametersListener";
  24. import { AbstractExpression } from "../MusicalScore/VoiceData/Expressions";
  25. export class ChannelNote {
  26. public note: PlaybackNote;
  27. public key: number;
  28. public channel: number;
  29. constructor(k: number, c: number, n: PlaybackNote = undefined) {
  30. this.note = n;
  31. this.key = k;
  32. this.channel = c;
  33. }
  34. }
  35. export class PlaybackManager implements IPlaybackParametersListener {
  36. protected timingSource: ITimingSource;
  37. protected resetRequested: boolean;
  38. protected loopTriggeredReset: boolean;
  39. protected tempoUserFactor: number;
  40. protected currentBPM: number;
  41. protected listeners: IPlaybackListener[] = [];
  42. public addListener(listener: IPlaybackListener): void {
  43. this.listeners.push(listener);
  44. }
  45. private readonly percussionChannel: number = 9; // this is a definition of the midi interface (cannot be changed)
  46. private messageViewer: IMessageViewer;
  47. private audioMetronomePlayer: IAudioMetronomePlayer;
  48. private audioPlayer: IAudioPlayer<any>;
  49. private musicPartManager: MusicPartManager;
  50. private cursorIterator: MusicPartManagerIterator;
  51. get Iterator(): MusicPartManagerIterator {
  52. return this.cursorIterator;
  53. }
  54. private playbackIterator: PlaybackIterator;
  55. //private Dictionary<int, MidiChannelInfo> instrumentsPerMidiSoundDict = new Dictionary<int, MidiChannelInfo>();
  56. //private Dictionary<int, int> midiSoundToChannelMappingDict = new Dictionary<int, int>();
  57. //private int[] midiChannelToSoundArray = new int[16];
  58. //Staff is not considered Unique for key purposes here. Had to use something unique - staff ID
  59. private instrumentToStaffToMidiChannelDict: Dictionary<Staff, number> = new Dictionary<Staff, number>();
  60. //store this data just in case
  61. private instrumentIdMapping: Dictionary<number, Instrument> = new Dictionary<number, Instrument>();
  62. public get InstrumentIdMapping(): Dictionary<number, Instrument> {
  63. return this.instrumentIdMapping;
  64. }
  65. //private List<int> staffIndexToMidiChannelMapping = new List<int>();
  66. private freeMidiChannels: number[] = [];
  67. private notesToStop: Dictionary<Fraction, ChannelNote[]> = new Dictionary<Fraction, ChannelNote[]>();
  68. private metronomeNote: ChannelNote = new ChannelNote(88, this.percussionChannel);
  69. private metronomeNoteFirstBeat: ChannelNote = new ChannelNote(64, this.percussionChannel);
  70. private currentMeasure: SourceMeasure = undefined;
  71. private currentTimestamp: Fraction = undefined;
  72. private closestNextTimestamp: Fraction = undefined;
  73. private currentMetronomeBaseTimestamp: Fraction = undefined;
  74. private currentBeatDuration: Fraction = undefined;
  75. private currentIteratorSourceTimeStamp: Fraction = undefined;
  76. private beatCounter: number = 0;
  77. protected runningState: PlaybackState = PlaybackState.Stopped;
  78. private isRunning: boolean = false;
  79. private isInitialized: boolean = false; // make sure midi device gets opened only once
  80. private nextIteratorTimestamp: Fraction;
  81. private playNextMetronomeAt: Fraction;
  82. // private masterTranspose: number = 0;
  83. private isPlaying: boolean = false;
  84. private metronome: MetronomeInstrument;
  85. private metronomeSoundPlayed: boolean = false;
  86. private tempoImpactFactor: number = 1.0;
  87. private sheetStartBPM: number;
  88. private currentReferenceBPM: number;
  89. private readonly defaultVolume: number = 0.8;
  90. private currentVolume: number = this.defaultVolume;
  91. private dynamicImpactFactor: number = 1.0;
  92. private scorePositionChangedData: CursorPosChangedData = new CursorPosChangedData();
  93. private tooManyInstruments: boolean = false;
  94. private currentRepetition: Repetition;
  95. private currentMeasureIndex: number;
  96. private metronomeOnlyBPM: number = 100;
  97. // private playbackThreadSyncObject = new object(); // TODO MB: Handle this.
  98. private readonly highlightPlayedNotes: boolean = false;
  99. private startRhythmBeats: number;
  100. private startRhythmDenominator: number;
  101. private isPreCounting: boolean;
  102. private fermataActive: boolean;
  103. private doPreCount: boolean = true;
  104. constructor (timingSource: ITimingSource, audioMetronomePlayer: IAudioMetronomePlayer, audioPlayer: IAudioPlayer<any>, messageViewer: IMessageViewer) {
  105. const metronomeLabel: string = TextTranslation.translateText("Playback/LabelMetronome", "Metronome");
  106. this.metronome = new MetronomeInstrument(-1, metronomeLabel, false, true, 0.0, MidiInstrument.Percussion);
  107. this.timingSource = timingSource;
  108. this.audioMetronomePlayer = audioMetronomePlayer;
  109. this.audioPlayer = audioPlayer;
  110. this.messageViewer = messageViewer;
  111. }
  112. public get RunningState(): PlaybackState {
  113. return this.runningState;
  114. }
  115. public set RunningState(value: PlaybackState) {
  116. this.runningState = value;
  117. }
  118. public DoPlayback: boolean;
  119. /** Do the initial pre-count */
  120. public get DoPreCount(): boolean {
  121. return this.doPreCount;
  122. }
  123. public set DoPreCount(value: boolean) {
  124. if (this.doPreCount !== value) {
  125. this.doPreCount = value;
  126. }
  127. }
  128. public PreCountBeats: number;
  129. public get Metronome(): ISettableInstrument {
  130. return this.metronome;
  131. }
  132. public get MetronomeOnlyBPM(): number {
  133. return this.metronomeOnlyBPM;
  134. }
  135. public set MetronomeOnlyBPM(value: number) {
  136. this.metronomeOnlyBPM = value;
  137. }
  138. // public get Transpose(): number {
  139. // return this.masterTranspose;
  140. // }
  141. // public set Transpose(value: number) {
  142. // this.masterTranspose = value;
  143. // }
  144. public get OriginalBpm(): number {
  145. return this.currentReferenceBPM;
  146. }
  147. /** will be activated when any solo flag of an Instrument, Voice or Staff is set to true. */
  148. public SoloActive: boolean;
  149. public SoloAttenuationValue: number = 0;
  150. // Only used for debug and scheduling precision measurements
  151. //private wantedNextIteratorTimestampMs: number = 0;
  152. public playVoiceEntry(voiceEntry: VoiceEntry): void {
  153. const ve: VoiceEntry = voiceEntry;
  154. if (ve !== undefined) {
  155. // lock(this.playbackThreadSyncObject) {
  156. this.stopAllCurrentlyPlayingNotes();
  157. if (this.highlightPlayedNotes) {
  158. const notes: Note[] = [];
  159. for (const note of ve.Notes) {
  160. note.state = NoteState.Selected;
  161. notes.push(note);
  162. }
  163. //this.NotesPlaybackEventOccurred(notes);
  164. }
  165. //int staffIndex = this.musicPartManager.MusicSheet.getIndexFromStaff(ve.Notes[0].ParentStaff);
  166. const channel: number = this.instrumentToStaffToMidiChannelDict.getValue(ve.Notes[0].ParentStaff);
  167. const instrument: Instrument = ve.ParentVoice.Parent;
  168. const isPercussion: boolean = instrument.MidiInstrumentId === MidiInstrument.Percussion;
  169. const volume: number = 0.8;
  170. const notesToPlay: ChannelNote[] = [];
  171. const transpose: number = this.musicPartManager.MusicSheet.Transpose;
  172. const instrumentPlaybackTranspose: number = ve.ParentVoice.Parent.PlaybackTranspose;
  173. for (const note of ve.MainPlaybackEntry.Notes.filter(n => n.MidiKey !== 0)) {
  174. // play the note
  175. let key: number = note.MidiKey;
  176. if (!isPercussion) {
  177. key += instrumentPlaybackTranspose + transpose;
  178. }
  179. if (note.ParentNote.PlaybackInstrumentId !== undefined) {
  180. const notePlaybackInstrument: SubInstrument =
  181. instrument.getSubInstrument(note.ParentNote.PlaybackInstrumentId);
  182. if (notePlaybackInstrument !== undefined) {
  183. if (notePlaybackInstrument.fixedKey >= 0) {
  184. key = notePlaybackInstrument.fixedKey;
  185. }
  186. }
  187. }
  188. // calculate stop time and remember it
  189. // const stopAt: Fraction = Fraction.plus(this.cursorIterator.CurrentEnrolledTimestamp, note.Length);
  190. try {
  191. if (this.audioPlayer !== undefined) {
  192. //const noteLengthFraction: Fraction = Fraction.createFromFraction(note.Length);
  193. this.audioPlayer.playSound(channel, key, volume, 500);
  194. }
  195. } catch (ex) {
  196. log.info("PlaybackManager.playVoiceEntry: ", ex);
  197. }
  198. notesToPlay.push(new ChannelNote(key, channel, note));
  199. }
  200. // TODO MB: Handle this
  201. // Task stopper = new Task(() => {
  202. // EventWaitHandle waiter = new EventWaitHandle(false, EventResetMode.AutoReset);
  203. // waiter.WaitOne(200);
  204. // lock(this.playbackThreadSyncObject) {
  205. // if (this.audioPlayer !== undefined) {
  206. // foreach(var n in notesToPlay) {
  207. // this.audioPlayer.stopSound(n.channel, n.key);
  208. // }
  209. // }
  210. // }
  211. // // redraw to color notes normal if highlighted in playback
  212. // //this.phonicScoreInterface.RedrawGraphicalMusicSheet();
  213. // });
  214. // stopper.Start();
  215. // }
  216. }
  217. }
  218. public initialize(musicPartMng: MusicPartManager): void {
  219. // lock(this.playbackThreadSyncObject) {
  220. if (this.isInitialized) {
  221. this.stopAllCurrentlyPlayingNotes();
  222. if (this.audioPlayer !== undefined) {
  223. this.audioPlayer.close();
  224. }
  225. this.cursorIterator = undefined;
  226. this.playbackIterator = undefined;
  227. }
  228. this.isInitialized = false;
  229. this.musicPartManager = musicPartMng;
  230. if (this.musicPartManager !== undefined) {
  231. const musicSheet: MusicSheet = this.musicPartManager.MusicSheet;
  232. // TODO MB: Converted musicSheetParameterChanged to setBpm in this file. Handle following line.
  233. //musicSheet.MusicSheetParameterChanged += this.musicSheetParameterChanged;
  234. this.cursorIterator = this.musicPartManager.getIterator();
  235. this.playbackIterator = new PlaybackIterator(musicSheet);
  236. if (this.audioPlayer !== undefined) {
  237. // TODO MB: I rewrote following line in line below. Does it do what it's supposed to do? Array.from() not supported in IE
  238. // List < MidiInstrument > uniqueMidiInstruments = musicSheet.Instruments.Select(item => item.MidiInstrumentId).Distinct().ToList();
  239. const uniqueMidiInstruments: MidiInstrument[] = Array.from(new Set(musicSheet.Instruments.map(item => item.MidiInstrumentId)));
  240. this.audioPlayer.open(uniqueMidiInstruments, 16);
  241. // set drums:
  242. this.audioPlayer.setSound(this.percussionChannel, 115);
  243. }
  244. this.currentReferenceBPM = this.sheetStartBPM = musicSheet.getExpressionsStartTempoInBPM();
  245. this.tempoUserFactor = musicSheet.userStartTempoInBPM / this.sheetStartBPM;
  246. let instrumentId: number = 0;
  247. this.tooManyInstruments = false;
  248. // reset the dicts and channel mappings
  249. //this.staffIndexToMidiChannelMapping.Clear();
  250. this.instrumentToStaffToMidiChannelDict.clear();
  251. this.instrumentIdMapping.clear();
  252. for (let i: number = 0; i < this.percussionChannel; i++) {
  253. this.freeMidiChannels.push(i);
  254. }
  255. for (let i: number = this.percussionChannel + 1; i < 16; i++) {
  256. this.freeMidiChannels.push(i);
  257. }
  258. for (const instrument of musicSheet.Instruments) {
  259. this.instrumentIdMapping.setValue(instrumentId, instrument);
  260. for (const staff of instrument.Staves) {
  261. // just add a list element - calcMidiChannel() will provide the right value.
  262. //this.staffIndexToMidiChannelMapping.Add(-1);
  263. this.instrumentToStaffToMidiChannelDict.setValue(staff, -1);
  264. }
  265. this.setSound(instrumentId, instrument.MidiInstrumentId);
  266. instrumentId++;
  267. }
  268. if (this.audioPlayer !== undefined && this.tooManyInstruments) {
  269. const errorMsg: string = TextTranslation.translateText(
  270. "MidiNumberError",
  271. "This music sheet has more parts than are supported for midi playback. " +
  272. "Some parts will not be played with the desired instrument sounds."
  273. );
  274. if (this.messageViewer !== undefined && this.messageViewer.MessageOccurred !== undefined) {
  275. this.messageViewer.MessageOccurred(MessageBoxType.Warning, errorMsg);
  276. }
  277. }
  278. this.checkForSoloDeactivated();
  279. }
  280. this.isInitialized = true;
  281. // }
  282. this.reset();
  283. }
  284. public async play(): Promise<void> {
  285. if (this.cursorIterator !== undefined && this.cursorIterator.EndReached) {
  286. console.log("End reached, resetting");
  287. this.reset();
  288. }
  289. this.isPlaying = true;
  290. this.RunningState = PlaybackState.Running;
  291. await this.timingSource.start();
  292. this.loop();
  293. }
  294. public async pause(): Promise<void> {
  295. // lock(this.playbackThreadSyncObject) {
  296. this.isPlaying = false;
  297. // stop all active midi notes:
  298. this.stopAllCurrentlyPlayingNotes();
  299. // inform sample player to e.g. dispose used samples:
  300. if (this.audioPlayer !== undefined) {
  301. this.audioPlayer.playbackHasStopped();
  302. }
  303. // notify delegates (coreContainer) that the playing has finished:
  304. this.RunningState = PlaybackState.Stopped;
  305. await this.timingSource.pause();
  306. try {
  307. //bool endReached = this.iterator !== undefined && this.iterator.EndReached;
  308. for (const listener of this.listeners) {
  309. listener.pauseOccurred(undefined);
  310. }
  311. } catch (ex) {
  312. log.debug("PlaybackManager.pause: ", ex);
  313. }
  314. // }
  315. }
  316. public reset(): void {
  317. // lock(this.playbackThreadSyncObject) {
  318. //this.resetRequested = true;
  319. this.doReset(this.DoPreCount);
  320. if (this.musicPartManager === undefined) {
  321. return;
  322. }
  323. if (this.RunningState === PlaybackState.Stopped) {
  324. //this.isPlaying = true;
  325. }
  326. for (const listener of this.listeners) {
  327. listener.resetOccurred(undefined);
  328. }
  329. // }
  330. }
  331. public Dispose(): void {
  332. // lock(this.playbackThreadSyncObject) {
  333. this.listeners = [];
  334. this.isRunning = false;
  335. // stop all active midi notes:
  336. if (this.isInitialized) {
  337. this.stopAllCurrentlyPlayingNotes();
  338. if (this.audioPlayer !== undefined) {
  339. this.audioPlayer.close();
  340. }
  341. }
  342. // this.musicPartManager = undefined;
  343. // // }
  344. }
  345. public setSound(instrumentId: number, newSoundId: MidiInstrument): boolean {
  346. if (newSoundId <= MidiInstrument.None || newSoundId > MidiInstrument.Percussion) {
  347. return false;
  348. }
  349. // lock(this.playbackThreadSyncObject) {
  350. try {
  351. const isPercussionNow: boolean = newSoundId === MidiInstrument.Percussion;
  352. if (instrumentId === -1) { // Metronome
  353. if (this.audioPlayer !== undefined && !isPercussionNow) {
  354. this.audioPlayer.setSound(0, newSoundId);
  355. }
  356. } else {
  357. let neededLastChannel: boolean = false;
  358. const musicSheet: MusicSheet = this.musicPartManager.MusicSheet;
  359. let instrument: Instrument;
  360. if (instrumentId === -2) {
  361. instrument = musicSheet.Instruments.find(x => x.Id === instrumentId);
  362. } else {
  363. instrument = musicSheet.Instruments[instrumentId];
  364. }
  365. this.instrumentIdMapping.setValue(instrument.Id, instrument);
  366. for (const staff of instrument.Staves) {
  367. //int staffIndex = musicSheet.getIndexFromStaff(staff);
  368. //int channel = this.staffIndexToMidiChannelMapping[staffIndex];
  369. let channel: number = this.instrumentToStaffToMidiChannelDict.getValue(staff);
  370. const wasPercussion: boolean = channel === this.percussionChannel;
  371. if (isPercussionNow) { // if is now a percussion
  372. const oldChannel: number = channel;
  373. channel = this.percussionChannel;
  374. // check if this instrument has been initialized and was no percussion instrument:
  375. if (oldChannel > 0 && !wasPercussion) {
  376. this.freeMidiChannels.push(oldChannel);
  377. this.freeMidiChannels.sort((a, b) => a - b); //TODO MB: Does this .sort do the same thing as C# .Sort()?
  378. }
  379. } else {
  380. if (channel < 0 || wasPercussion) { // if is not initialized or was a percussion:
  381. if (this.freeMidiChannels.length > 0) { // if still a free channel exists
  382. // get the channel and remove in from the free channels list
  383. channel = this.freeMidiChannels[0];
  384. this.freeMidiChannels.shift();
  385. } else { // if no channel is free any more:
  386. this.tooManyInstruments = true;
  387. // use last channel
  388. channel = 15;
  389. this.instrumentToStaffToMidiChannelDict.setValue(staff, channel);
  390. //// use piano sound
  391. //newSoundId = 0;
  392. neededLastChannel = true;
  393. }
  394. }
  395. }
  396. this.instrumentToStaffToMidiChannelDict.setValue(staff, channel);
  397. if (this.audioPlayer !== undefined && !isPercussionNow) {
  398. // TODO: Uncomment when panaroma is supported in audio player
  399. // this.audioPlayer.setPanorama(channel, instrument.SubInstruments[0].pan);
  400. // TODO: Commented because AvailableComponents not defined
  401. // if (AvailableComponents.PLAYBACK_INSTRUMENTS_AVAILABLE) {
  402. // // only set instrument sounds in pro version:
  403. this.audioPlayer.setSound(channel, newSoundId);
  404. // } else {
  405. // play all as piano in free version:
  406. // this.audioPlayer.setSound(channel, 0);
  407. // }
  408. }
  409. }
  410. if (neededLastChannel) {
  411. return false;
  412. }
  413. }
  414. return true;
  415. } catch (ex) {
  416. log.info("PlaybackManager.setSound: ", ex);
  417. return false;
  418. }
  419. // }
  420. }
  421. // public mainParameterChanged(client: IPhonicScoreClient, settingType: ProgramParameters, currentValue, previousValue): void {
  422. // switch (settingType) {
  423. // case ProgramParameters.DynamicInstructionsImpact:
  424. // this.dynamicImpactFactor = Convert.ToSingle(currentValue);
  425. // break;
  426. // case ProgramParameters.TempoInstructionsImpact: {
  427. // this.tempoImpactFactor = Convert.ToSingle(currentValue);
  428. // this.setTempo();
  429. // break;
  430. // }
  431. // }
  432. // }
  433. // TODO MB: Check if function setBpm() is sufficient for doing what commented function below does.
  434. // protected musicSheetParameterChanged(client: IPhonicScoreClient, parameter: MusicSheetParameters, currentValue, previousValue): void {
  435. // switch (parameter) {
  436. // case MusicSheetParameters.StartTempoInBPM: {
  437. // this.tempoUserFactor = Convert.ToSingle(currentValue) / this.sheetStartBPM;
  438. // this.setTempo();
  439. // break;
  440. // }
  441. // }
  442. // }
  443. protected setBpm(bpm: number): void {
  444. this.tempoUserFactor = bpm / this.sheetStartBPM;
  445. this.setTempo();
  446. }
  447. public handlePlaybackEvent(): void {
  448. // lock(this.playbackThreadSyncObject) {
  449. // initialize flags:
  450. const resetOccurred: boolean = this.resetRequested;
  451. this.resetRequested = false;
  452. // const resetMetronomeBeatCounter: boolean = resetOccurred;
  453. // @ts-ignore
  454. const resetMetronomeBeatCounter: boolean = resetOccurred;
  455. let updateCursorPosition: boolean = resetOccurred;
  456. let endHasBeenReached: boolean = false;
  457. if (resetOccurred) {
  458. const shallPrecount: boolean = this.DoPreCount;
  459. this.doReset(shallPrecount);
  460. }
  461. if (this.musicPartManager === undefined) {
  462. return;
  463. }
  464. /**********************************************/
  465. // set the current values:
  466. this.currentTimestamp = this.timingSource.getCurrentTimestamp();
  467. // console.log("TS ms: " + this.timingSource.getCurrentTimeInMs());
  468. // console.log("TS ts: " + this.currentTimestamp);
  469. endHasBeenReached = this.cursorIterator.EndReached;
  470. /**********************************************/
  471. // handle the currently pending instructions:
  472. // stop the notes that are already over now:
  473. this.stopFinishedNotes();
  474. /***** process tempo instructions: *****/
  475. this.processTempoInstructions();
  476. if (this.RunningState === PlaybackState.Running) { // needed when resetting when in pause
  477. const newCursorTimestampReached: boolean = this.currentTimestamp.gte(this.cursorIterator.CurrentEnrolledTimestamp)
  478. && !endHasBeenReached;
  479. if (newCursorTimestampReached) {
  480. this.isPreCounting = false;
  481. /***** Metronome Beat Calculations *****/
  482. // check if the measure has changed:
  483. if (this.currentMeasure !== this.cursorIterator.CurrentMeasure &&
  484. this.cursorIterator.CurrentMeasure !== undefined) {
  485. // set current measure to the new measure
  486. this.currentMeasure = this.cursorIterator.CurrentMeasure;
  487. this.startRhythmBeats = this.cursorIterator.currentPlaybackSettings().Rhythm.Numerator;
  488. this.startRhythmDenominator = this.cursorIterator.currentPlaybackSettings().Rhythm.Denominator;
  489. // get the enrolled timestamp of this measure start:
  490. const relativeToMeasureTimestamp: Fraction = this.cursorIterator.CurrentRelativeInMeasureTimestamp;
  491. this.currentMetronomeBaseTimestamp = Fraction.minus(this.cursorIterator.CurrentEnrolledTimestamp, relativeToMeasureTimestamp);
  492. // calculate the new beat duration
  493. this.currentBeatDuration = new Fraction(1, this.currentMeasure.Duration.Denominator);
  494. // calculate which beat is next:
  495. const relativeNextMetronomeBeatTimestamp: Fraction = new Fraction();
  496. this.beatCounter = 0;
  497. while (relativeNextMetronomeBeatTimestamp.lt(relativeToMeasureTimestamp)) {
  498. relativeNextMetronomeBeatTimestamp.Add(this.currentBeatDuration);
  499. this.beatCounter++;
  500. }
  501. this.playNextMetronomeAt = Fraction.plus(
  502. this.currentMetronomeBaseTimestamp,
  503. new Fraction(this.beatCounter, this.currentMeasure.Duration.Denominator)
  504. );
  505. }
  506. /***** process dynamic instructions: *****/
  507. const dynamicEntries: DynamicsContainer[] = this.cursorIterator.getCurrentDynamicChangingExpressions();
  508. for (const dynamicEntry of dynamicEntries) {
  509. const staff: Staff = this.musicPartManager.MusicSheet.getStaffFromIndex(dynamicEntry.staffNumber);
  510. const channel: number =
  511. this.instrumentToStaffToMidiChannelDict.getValue(staff);
  512. //int channel = this.staffIndexToMidiChannelMapping[dynamicEntry.StaffNumber];
  513. let volume: number = this.currentVolume;
  514. if (dynamicEntry.parMultiExpression().StartingContinuousDynamic !== undefined) {
  515. // dynamic expression is continuous:
  516. const currentDynamicValue: number =
  517. dynamicEntry.parMultiExpression().StartingContinuousDynamic.getInterpolatedDynamic(
  518. this.cursorIterator.CurrentSourceTimestamp);
  519. if (currentDynamicValue >= 0) {
  520. volume = this.calculateFinalVolume(currentDynamicValue);
  521. }
  522. } else { // dynamic Expression is instantanious - immediately set the volume:
  523. volume = this.calculateFinalVolume(dynamicEntry.parMultiExpression().InstantaneousDynamic.Volume);
  524. }
  525. try {
  526. if (this.audioPlayer !== undefined) {
  527. this.audioPlayer.setVolume(channel, volume);
  528. }
  529. } catch (ex) {
  530. log.info("PlaybackManager.handlePlaybackEvent: ", ex);
  531. }
  532. }
  533. dynamicEntries.clear();
  534. }
  535. // check if the time has come to process the pending instructions:
  536. const dueEntries: { enrolledTimestamp: Fraction, playbackEntry: PlaybackEntry }[] = this.playbackIterator.Update(this.currentTimestamp);
  537. if (dueEntries.length > 0) {
  538. // play new notes
  539. if (this.DoPlayback) {
  540. const playbackedNotes: PlaybackNote[] = [];
  541. for (const entry of dueEntries) {
  542. const playbackEntry: PlaybackEntry = entry.playbackEntry;
  543. const voiceEntry: VoiceEntry = playbackEntry.ParentVoiceEntry;
  544. if (playbackEntry.Notes.length === 0) {
  545. continue;
  546. }
  547. const instrument: Instrument = voiceEntry.ParentVoice.Parent;
  548. const staff: Staff = voiceEntry.Notes[0].ParentStaff;
  549. const staffIndex: number =
  550. MusicSheet.getIndexFromStaff(staff);
  551. let channel: number = this.instrumentToStaffToMidiChannelDict.getValue(staff);
  552. const isPercussion: boolean = instrument.MidiInstrumentId === MidiInstrument.Percussion;
  553. // choose percussion channel if Selected
  554. if (isPercussion) {
  555. channel = this.percussionChannel;
  556. }
  557. const currentlyActiveExpression: AbstractExpression = this.cursorIterator.ActiveDynamicExpressions[staffIndex];
  558. // adapt volume level for continuous expressions
  559. if (currentlyActiveExpression instanceof ContinuousDynamicExpression) {
  560. const currentDynamicValue: number =
  561. currentlyActiveExpression.getInterpolatedDynamic(
  562. this.cursorIterator.CurrentSourceTimestamp);
  563. if (currentDynamicValue >= 0) {
  564. const channelVolume: number = this.calculateFinalVolume(currentDynamicValue);
  565. try {
  566. if (this.audioPlayer !== undefined) {
  567. this.audioPlayer.setVolume(channel, channelVolume);
  568. }
  569. } catch (ex) {
  570. log.info("PlaybackManager.handlePlaybackEvent: ", ex);
  571. }
  572. }
  573. }
  574. // calculate volume from instrument volume, staff volume and voice volume:
  575. let volume: number = instrument.Volume * staff.Volume * voiceEntry.ParentVoice.Volume;
  576. // attenuate if in Solo mode an this voice is not soloed:
  577. const soloAttenuate: boolean = this.SoloActive &&
  578. !(instrument.Solo || voiceEntry.ParentVoice.Solo || staff.Solo);
  579. if (soloAttenuate) {
  580. volume *= this.SoloAttenuationValue;
  581. }
  582. // increase volume if this is an accent:
  583. const entryIsAccent: boolean = voiceEntry.VolumeModifier !== undefined;
  584. if (entryIsAccent) {
  585. volume *= 1.3;
  586. volume = Math.min(1, volume);
  587. }
  588. const transpose: number = this.musicPartManager.MusicSheet.Transpose;
  589. const instrumentPlaybackTranspose: number = instrument.PlaybackTranspose ?? 0;
  590. for (const note of playbackEntry.Notes.filter(n => n.MidiKey !== 0)) {
  591. // play the note
  592. let key: number = note.MidiKey;
  593. if (!isPercussion) {
  594. key += instrumentPlaybackTranspose + transpose;
  595. }
  596. // if note has another explicitly given playback instrument:
  597. if (note.ParentNote.PlaybackInstrumentId !== undefined) {
  598. // playback with other instrument:
  599. const notePlaybackInstrument: SubInstrument =
  600. instrument.getSubInstrument(note.ParentNote.PlaybackInstrumentId);
  601. if (notePlaybackInstrument !== undefined) {
  602. if (notePlaybackInstrument.fixedKey >= 0) {
  603. key = notePlaybackInstrument.fixedKey;
  604. }
  605. }
  606. // recalculate Volume for this instrument:
  607. volume = notePlaybackInstrument.volume * staff.Volume * voiceEntry.ParentVoice.Volume;
  608. // attenuate if in Solo mode an this voice is not soloed:
  609. if (soloAttenuate) {
  610. volume *= this.SoloAttenuationValue;
  611. }
  612. if (entryIsAccent) {
  613. volume *= 1.3;
  614. volume = Math.min(1, volume);
  615. }
  616. }
  617. // calculate stop time and remember it
  618. let noteLength: Fraction = Fraction.createFromFraction(note.Length);
  619. let stopAt: Fraction;
  620. // ToDo MU: move this to PlaybackEntry
  621. const entryIsStaccato: boolean = voiceEntry.DurationModifier !== undefined;
  622. if (entryIsStaccato) {
  623. // Reduce length and stopAt time:
  624. noteLength = new Fraction(noteLength.Numerator * 2, noteLength.Denominator * 3);
  625. stopAt = Fraction.plus(entry.enrolledTimestamp, noteLength);
  626. } else {
  627. stopAt = Fraction.plus(entry.enrolledTimestamp, noteLength);
  628. }
  629. try {
  630. if (this.audioPlayer !== undefined) {
  631. this.audioPlayer.playSound( channel,
  632. key,
  633. volume,
  634. this.timingSource.getDurationInMs(noteLength));
  635. }
  636. } catch (ex) {
  637. log.info("PlaybackManager.handlePlaybackEvent. Failed playing sound: ", ex);
  638. }
  639. if (!this.notesToStop.containsKey(stopAt)) {
  640. // this.notesToStop.Add(stopAt, new List<ChannelNote>());
  641. this.notesToStop.setValue(stopAt, []);
  642. }
  643. this.notesToStop.getValue(stopAt).push(new ChannelNote(key, channel, note));
  644. if (this.highlightPlayedNotes) {
  645. note.ParentNote.state = NoteState.Selected;
  646. }
  647. playbackedNotes.push(note);
  648. }
  649. }
  650. /*** Inform about which notes are now played ***
  651. * e.g. for updating graphics
  652. */
  653. // TODO: Replace with generic event system
  654. // if (this.highlightPlayedNotes && this.NotesPlaybackEventOccurred !== undefined) {
  655. this.NotesPlaybackEventOccurred(playbackedNotes);
  656. }
  657. }
  658. if (newCursorTimestampReached) {
  659. // store current iterator parameters:
  660. this.currentIteratorSourceTimeStamp = this.cursorIterator.CurrentSourceTimestamp;
  661. this.currentMeasureIndex = this.cursorIterator.CurrentMeasureIndex;
  662. // this.currentRepetition = this.cursorIterator.CurrentRepetition;
  663. /************ Move to next sheet position ************/
  664. // move iterator already to next position, to find out how long to wait or if the End has been reached:
  665. this.cursorIterator.moveToNext();
  666. this.nextIteratorTimestamp = this.cursorIterator.CurrentEnrolledTimestamp;
  667. updateCursorPosition = true;
  668. }
  669. // Stop the sound of the last played metronome
  670. this.stopMetronomeSound();
  671. // Check for "end has been reached"
  672. if (endHasBeenReached && this.currentTimestamp.gte(this.cursorIterator.CurrentEnrolledTimestamp)) {
  673. // notify possible listeners:
  674. for (const listener of this.listeners) {
  675. listener.selectionEndReached(undefined);
  676. }
  677. this.handleEndReached();
  678. } else {
  679. /******
  680. * Play Metronome if needed
  681. */
  682. if (this.currentTimestamp.gte(this.playNextMetronomeAt)) {
  683. updateCursorPosition = true;
  684. const playFirstBeatSample: boolean = this.beatCounter % this.startRhythmBeats === 0;
  685. this.playMetronomeSound(playFirstBeatSample);
  686. this.beatCounter++;
  687. }
  688. // calculate the next metronome beat timestamp
  689. if (this.currentMetronomeBaseTimestamp !== undefined) {
  690. this.playNextMetronomeAt = Fraction.plus(
  691. this.currentMetronomeBaseTimestamp,
  692. new Fraction(this.beatCounter, this.startRhythmDenominator)
  693. );
  694. }
  695. /*************************************/
  696. this.calculateClosestNextTimestamp();
  697. }
  698. } else {
  699. // needed when a reset was requested: reset parameters, fire score position changed and finally stop again
  700. this.isPlaying = false;
  701. }
  702. // Check for "updating the display"
  703. if (updateCursorPosition ||
  704. endHasBeenReached && !this.loopTriggeredReset) {
  705. // set the play cursor in the display
  706. this.updateScoreCursorPosition(resetOccurred);
  707. }
  708. // }
  709. }
  710. private NotesPlaybackEventOccurred(notes: PlaybackNote[]): void {
  711. for (const listener of this.listeners) {
  712. listener.notesPlaybackEventOccurred(notes);
  713. }
  714. }
  715. public calculateFinalVolume(volume: number): number {
  716. return ((volume - this.defaultVolume) * this.dynamicImpactFactor + this.defaultVolume);
  717. }
  718. // TODO unused!?
  719. // @ts-ignore
  720. private loop(): void {
  721. // start playing:
  722. try {
  723. this.isRunning = true;
  724. // @ts-ignore
  725. const reset: boolean = false;
  726. if (this.isPlaying) {
  727. try {
  728. if (this.isRunning && this.isInitialized) {
  729. //console.log(`handlePlayback, timing deviation: ${Math.round(this.timingSource.getCurrentTimeInMs()) - Math.round(this.wantedNextIteratorTimestampMs)}`);
  730. this.handlePlaybackEvent();
  731. if (this.closestNextTimestamp !== undefined) {
  732. const wantedNextElapsedMs: number = this.timingSource.getWaitingTimeForTimestampInMs(this.closestNextTimestamp);
  733. //this.wantedNextIteratorTimestampMs = this.timingSource.getCurrentTimeInMs() + wantedNextElapsedMs;
  734. window.setTimeout(() => { this.loop(); }, Math.max(0, wantedNextElapsedMs));
  735. //this.interruptWaiting.WaitOne(Math.max(0, wantedNextElapsedMs));
  736. }
  737. }
  738. } catch (ex) {
  739. this.pause();
  740. this.reset();
  741. const errorMsg: string = TextTranslation.translateText(
  742. "MidiPlaybackError",
  743. "An error occurred at the Midi Playback."
  744. );
  745. log.info("PlaybackManager.loop: " + errorMsg + " ", ex);
  746. if (this.messageViewer !== undefined && this.messageViewer.MessageOccurred !== undefined) {
  747. this.messageViewer.MessageOccurred(MessageBoxType.Error, errorMsg);
  748. }
  749. }
  750. }
  751. } catch (ex) {
  752. const errorMsg: string = TextTranslation.translateText(
  753. "MidiPlaybackLoopError",
  754. "An error occurred at the Midi Playback. Please restart the program in order for the Playback to be availiable again."
  755. );
  756. log.info("PlaybackManager.loop: " + errorMsg + " ", ex);
  757. if (this.messageViewer !== undefined && this.messageViewer.MessageOccurred !== undefined) {
  758. this.messageViewer.MessageOccurred(MessageBoxType.Error, errorMsg);
  759. }
  760. }
  761. this.isRunning = false;
  762. }
  763. private stopAllCurrentlyPlayingNotes(): void {
  764. try {
  765. // lock(this.playbackThreadSyncObject) {
  766. if (this.audioPlayer !== undefined) {
  767. // stop active metronome sound
  768. this.audioPlayer.stopSound(this.metronomeNoteFirstBeat.channel, this.metronomeNoteFirstBeat.key);
  769. this.audioPlayer.stopSound(this.metronomeNote.channel, this.metronomeNote.key);
  770. // stop active notes
  771. // TODO MB: check if port of following for..of is correct
  772. // check same in for..of below
  773. // for (const entry of this.notesToStop) {
  774. // for (const note of entry.Value) {
  775. // this.audioPlayer.stopSound(note.channel, note.key);
  776. // }
  777. // }
  778. for (const entry of this.notesToStop.values()) {
  779. for (const note of entry) {
  780. this.audioPlayer.stopSound(note.channel, note.key);
  781. }
  782. }
  783. }
  784. /*** Inform about which notes are now stopped ***
  785. * e.g. for updating graphics
  786. */
  787. const notes: Note[] = [];
  788. for (const entry of this.notesToStop.values()) {
  789. for (const note of entry) {
  790. note.note.ParentNote.state = NoteState.Normal;
  791. notes.push(note.note.ParentNote);
  792. }
  793. }
  794. if (this.highlightPlayedNotes) {
  795. // TODO: Replace with generic even system
  796. // if (this.NotesPlaybackEventOccurred !== undefined) {
  797. // this.NotesPlaybackEventOccurred(notes);
  798. // }
  799. }
  800. this.notesToStop.clear();
  801. // }
  802. } catch (ex) {
  803. log.info("PlaybackManager.stoppAllCurrentlyPlayingNotes: ", ex);
  804. }
  805. }
  806. protected doReset(shallPrecount: boolean): void {
  807. this.nextIteratorTimestamp = undefined;
  808. this.playNextMetronomeAt = undefined;
  809. this.closestNextTimestamp = undefined;
  810. this.currentMeasure = undefined;
  811. this.beatCounter = 0;
  812. this.fermataActive = false;
  813. this.stopAllCurrentlyPlayingNotes();
  814. if (this.musicPartManager !== undefined) {
  815. this.cursorIterator = this.musicPartManager.getIterator();
  816. }
  817. if (this.cursorIterator === undefined) {
  818. return;
  819. }
  820. this.playbackIterator.Reset();
  821. this.currentIteratorSourceTimeStamp = this.cursorIterator.CurrentSourceTimestamp;
  822. this.nextIteratorTimestamp = this.cursorIterator.CurrentEnrolledTimestamp;
  823. this.currentMeasure = this.cursorIterator.CurrentMeasure;
  824. this.currentMeasureIndex = this.cursorIterator.CurrentMeasureIndex;
  825. // this.currentRepetition = this.cursorIterator.CurrentRepetition;
  826. this.startRhythmBeats = this.cursorIterator.currentPlaybackSettings().Rhythm.Numerator;
  827. this.startRhythmDenominator = this.cursorIterator.currentPlaybackSettings().Rhythm.Denominator;
  828. let preCountDuration: Fraction = new Fraction();
  829. if (shallPrecount) {
  830. this.isPreCounting = true;
  831. const rhythmDuration: Fraction = new Fraction(this.startRhythmBeats, this.startRhythmDenominator);
  832. const duration: Fraction =
  833. Fraction.plus( this.musicPartManager.MusicSheet.SourceMeasures[this.currentMeasureIndex].AbsoluteTimestamp,
  834. this.musicPartManager.MusicSheet.SourceMeasures[this.currentMeasureIndex].Duration).Sub(this.currentIteratorSourceTimeStamp);
  835. preCountDuration = rhythmDuration;
  836. if (rhythmDuration.gte(duration)) { // make sure that missing duration can't get negative (e.g. if measure is longer that given rhythm.
  837. const missingDuration: Fraction = Fraction.minus(rhythmDuration, duration);
  838. if (missingDuration.RealValue / rhythmDuration.RealValue < 0.5) {
  839. preCountDuration.Add(missingDuration);
  840. } else {
  841. preCountDuration = missingDuration;
  842. }
  843. }
  844. }
  845. this.currentMetronomeBaseTimestamp = this.playNextMetronomeAt = Fraction.minus(this.cursorIterator.CurrentEnrolledTimestamp, preCountDuration);
  846. //this.timingSource.Reset();
  847. this.timingSource.setTimeAndBpm(this.currentMetronomeBaseTimestamp,
  848. this.cursorIterator.currentPlaybackSettings().BeatsPerMinute);
  849. this.calculateClosestNextTimestamp();
  850. }
  851. /// <summary>
  852. /// Calculate the closest next timestamp at which the next instruction has to be processed
  853. /// </summary>
  854. private calculateClosestNextTimestamp(): void {
  855. const timestamps: Fraction[] = [];
  856. // add next timestamp for stopping notes
  857. if (this.notesToStop.size() > 0) {
  858. // timestamps.push(this.notesToStop.keys().Min());
  859. // TODO MB: Check if line below does what line above is supposed to do
  860. timestamps.push(this.notesToStop.keys().reduce( (a, b) => a.lt(b) ? a : b));
  861. }
  862. // add next timestamp for next notes or other sheet instruction
  863. if (this.playbackIterator.NextEntryTimestamp !== undefined) {
  864. timestamps.push(this.playbackIterator.NextEntryTimestamp);
  865. }
  866. if (this.nextIteratorTimestamp !== undefined) {
  867. timestamps.push(this.nextIteratorTimestamp);
  868. }
  869. // add next timestamp for metronome tick
  870. if (this.playNextMetronomeAt !== undefined) {
  871. timestamps.push(this.playNextMetronomeAt);
  872. }
  873. // get the closest next timestamp
  874. if (timestamps.length > 0) {
  875. // this.closestNextTimestamp = timestamps.Min();
  876. // TODO MB: Check if line below does what line above is supposed to do
  877. this.closestNextTimestamp = timestamps.reduce( (a, b) => a.lt(b) ? a : b);
  878. } else {
  879. this.closestNextTimestamp = undefined;
  880. }
  881. }
  882. /// <summary>
  883. /// Called when the end of the sheet or the selection has been reached
  884. /// </summary>
  885. protected handleEndReached(): void {
  886. this.pause();
  887. }
  888. /// <summary>
  889. /// Fire a delegate to inform the display, that the cursor position has changed
  890. /// </summary>
  891. /// <param name="resetOccurred"></param>
  892. private updateScoreCursorPosition(resetOccurred: boolean): void {
  893. this.scorePositionChangedData.CurrentMeasureIndex = this.currentMeasureIndex;
  894. this.scorePositionChangedData.CurrentRepetition = this.currentRepetition;
  895. this.scorePositionChangedData.PredictedPosition = this.currentTimestamp;
  896. this.scorePositionChangedData.CurrentBpm = this.musicPartManager.MusicSheet.SheetPlaybackSetting.BeatsPerMinute;
  897. this.scorePositionChangedData.ResetOccurred = resetOccurred;
  898. for (const listener of this.listeners) {
  899. listener.cursorPositionChanged(this.currentIteratorSourceTimeStamp, this.scorePositionChangedData);
  900. }
  901. }
  902. private stopMetronomeSound(): void {
  903. if (this.metronomeSoundPlayed) {
  904. if (this.audioPlayer !== undefined) {
  905. this.audioPlayer.stopSound(this.metronomeNoteFirstBeat.channel, this.metronomeNoteFirstBeat.key);
  906. this.audioPlayer.stopSound(this.metronomeNote.channel, this.metronomeNote.key);
  907. }
  908. this.metronomeSoundPlayed = false;
  909. }
  910. }
  911. private playMetronomeSound(playFirstBeatSample: boolean): void {
  912. // play the metronome if needed:
  913. if (this.metronome.Audible ||
  914. this.metronome.Solo ||
  915. this.isPreCounting) {
  916. let volume: number = this.metronome.Volume;
  917. if (!this.isPreCounting && this.SoloActive && !this.metronome.Solo) {
  918. volume *= this.SoloAttenuationValue;
  919. }
  920. if (volume > 0) {
  921. if (playFirstBeatSample) {
  922. try {
  923. if (this.audioPlayer !== undefined) {
  924. this.audioPlayer.playSound(this.metronomeNoteFirstBeat.channel, this.metronomeNoteFirstBeat.key, volume, 1000);
  925. }
  926. if (this.audioMetronomePlayer !== undefined) {
  927. this.audioMetronomePlayer.playFirstBeatSample(volume);
  928. }
  929. } catch (ex) {
  930. log.info("PlaybackManager.playMetronomeSound: ", ex);
  931. }
  932. } else {
  933. try {
  934. if (this.audioPlayer !== undefined) {
  935. this.audioPlayer.playSound(this.metronomeNote.channel, this.metronomeNote.key, volume, 1000);
  936. }
  937. if (this.audioMetronomePlayer !== undefined) {
  938. this.audioMetronomePlayer.playBeatSample(volume);
  939. }
  940. } catch (ex) {
  941. log.info("PlaybackManager.playMetronomeSound: ", ex);
  942. }
  943. }
  944. this.metronomeSoundPlayed = true;
  945. }
  946. }
  947. }
  948. private stopFinishedNotes(): void {
  949. // do the pending note stops:
  950. let expiredKeys: Fraction[];
  951. if (this.currentTimestamp !== undefined) {
  952. expiredKeys = this.notesToStop.keys().filter(ts => ts.lte(this.currentTimestamp));
  953. } else {
  954. expiredKeys = this.notesToStop.keys();
  955. }
  956. for (const timestamp of expiredKeys) {
  957. const notesToStop: ChannelNote[] = this.notesToStop.getValue(timestamp);
  958. if (this.audioPlayer !== undefined) {
  959. for (const note of notesToStop) {
  960. this.audioPlayer.stopSound(note.channel, note.key);
  961. }
  962. }
  963. /*** Inform about which notes are now stopped ***
  964. * e.g. for updating graphics
  965. */
  966. const notes: Note[] = [];
  967. for (const note of notesToStop) {
  968. note.note.ParentNote.state = NoteState.Normal;
  969. notes.push(note.note.ParentNote);
  970. }
  971. if (this.highlightPlayedNotes) {
  972. // TODO: Replace with generic event system
  973. // if (this.NotesPlaybackEventOccurred !== undefined) {
  974. // this.NotesPlaybackEventOccurred(notes);
  975. // }
  976. }
  977. this.notesToStop.remove(timestamp);
  978. }
  979. }
  980. private processTempoInstructions(): void {
  981. // 1. check if the current bpm of the iterator have changed (significantly):
  982. if (Math.abs(this.currentReferenceBPM - this.cursorIterator.CurrentBpm) > 0.001) {
  983. this.changeTempo(this.cursorIterator.CurrentBpm);
  984. }
  985. // 2. check for possible fermatas and slow down for that entry:
  986. this.handleFermata();
  987. }
  988. private handleFermata(): void {
  989. // check for fermatas:
  990. let fermataFound: boolean = false;
  991. if (!this.cursorIterator.EndReached) {
  992. if (this.currentTimestamp.gte(this.cursorIterator.CurrentEnrolledTimestamp)) {
  993. for (const ve of this.cursorIterator.CurrentVoiceEntries) {
  994. fermataFound = ve.Fermata !== undefined;
  995. }
  996. }
  997. }
  998. if (fermataFound) {
  999. if (!this.fermataActive) {
  1000. this.fermataActive = true;
  1001. this.changeTempo(this.cursorIterator.CurrentBpm / 3);
  1002. }
  1003. } else {
  1004. if (this.fermataActive) {
  1005. this.fermataActive = false;
  1006. this.changeTempo(this.cursorIterator.CurrentBpm);
  1007. }
  1008. }
  1009. }
  1010. public bpmChanged(newBpm: number): void {
  1011. this.currentBPM = newBpm;
  1012. this.timingSource.setBpm(newBpm);
  1013. }
  1014. public volumeChanged(instrument: number, newVolume: number): void {
  1015. this.currentVolume = newVolume / 100;
  1016. if (instrument === -1) {
  1017. this.metronome.Volume = this.currentVolume;
  1018. } else {
  1019. this.instrumentIdMapping.getValue(instrument).Volume = this.currentVolume;
  1020. }
  1021. }
  1022. public volumeMute(instrument: number): void {
  1023. if (instrument === -1) {
  1024. this.metronome.Mute = true;
  1025. } else {
  1026. this.instrumentIdMapping.getValue(instrument).Audible = false;
  1027. }
  1028. }
  1029. public volumeUnmute(instrument: number): void {
  1030. if (instrument === -1) {
  1031. this.metronome.Mute = false;
  1032. } else {
  1033. this.instrumentIdMapping.getValue(instrument).Audible = true;
  1034. }
  1035. }
  1036. private changeTempo(newTempoInBPM: number): void {
  1037. log.debug("PlaybackManager.changeTempo", `current tempo in BPM: ${newTempoInBPM}`);
  1038. //Console.WriteLine(currTempoInBPM.ToString());
  1039. if (newTempoInBPM > 0) {
  1040. this.currentReferenceBPM = newTempoInBPM;
  1041. this.setTempo();
  1042. }
  1043. }
  1044. protected setTempo(): void {
  1045. this.currentBPM = this.tempoUserFactor * this.getCurrentReferenceBPM();
  1046. this.timingSource.setBpm(this.currentBPM);
  1047. }
  1048. protected getCurrentReferenceBPM(): number {
  1049. return ((this.currentReferenceBPM - this.sheetStartBPM) * this.tempoImpactFactor + this.sheetStartBPM);
  1050. }
  1051. public checkForSoloDeactivated(): void {
  1052. if (this.musicPartManager.MusicSheet === undefined) {
  1053. this.SoloActive = false;
  1054. return;
  1055. }
  1056. let state: boolean = false;
  1057. for (const instrument of this.musicPartManager.MusicSheet.Instruments) {
  1058. for (const staff of instrument.Staves) {
  1059. state = state || staff.Solo;
  1060. }
  1061. for (const voice of instrument.Voices) {
  1062. state = state || voice.Solo;
  1063. }
  1064. }
  1065. state = state || this.Metronome.Solo;
  1066. if (!state) {
  1067. this.SoloActive = false;
  1068. }
  1069. }
  1070. //private class MidiChannelInfo
  1071. //{
  1072. // public List<IInstrument> subscribers = new List<IInstrument>();
  1073. // public int channel;
  1074. //}
  1075. }