2022-12-05 03:16:48 -05:00
|
|
|
|
2022-11-29 07:54:03 -05:00
|
|
|
const { Midi } = require('@tonejs/midi')
|
|
|
|
const { convertNote, convertPercussionNote } = require('./convert_note.js')
|
2022-08-14 05:51:45 -04:00
|
|
|
|
2022-11-29 07:54:03 -05:00
|
|
|
function convertMidi (midi) {
|
|
|
|
if (!(midi instanceof Midi)) throw new TypeError('midi must be an instance of require(\'@tonejs/midi\').Midi')
|
2022-08-14 05:51:45 -04:00
|
|
|
|
2022-11-29 07:54:03 -05:00
|
|
|
let noteList = []
|
2022-08-14 05:51:45 -04:00
|
|
|
for (const track of midi.tracks) {
|
|
|
|
for (const note of track.notes) {
|
2022-11-29 07:54:03 -05:00
|
|
|
const mcNote = (track.instrument.percussion ? convertPercussionNote : convertNote)(track, note)
|
2022-08-14 05:51:45 -04:00
|
|
|
if (mcNote != null) {
|
2022-11-29 07:54:03 -05:00
|
|
|
noteList.push(mcNote)
|
2022-08-14 05:51:45 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-29 07:54:03 -05:00
|
|
|
noteList = noteList.sort((a, b) => a.time - b.time)
|
2022-08-14 05:51:45 -04:00
|
|
|
|
|
|
|
// It might be better to move some of this code to the converting loop (for performance reasons)
|
2022-11-29 07:54:03 -05:00
|
|
|
let maxVolume = 0.001
|
2022-08-14 05:51:45 -04:00
|
|
|
for (const note of noteList) {
|
2022-11-29 07:54:03 -05:00
|
|
|
if (note.volume > maxVolume) maxVolume = note.volume
|
2022-08-14 05:51:45 -04:00
|
|
|
}
|
|
|
|
for (const note of noteList) {
|
2022-11-29 07:54:03 -05:00
|
|
|
note.volume /= maxVolume
|
2022-08-14 05:51:45 -04:00
|
|
|
}
|
|
|
|
|
2022-11-29 07:54:03 -05:00
|
|
|
let songLength = 0
|
2022-08-14 05:51:45 -04:00
|
|
|
for (const note of noteList) {
|
2022-11-29 07:54:03 -05:00
|
|
|
if (note.time > songLength) songLength = note.time
|
2022-08-14 05:51:45 -04:00
|
|
|
}
|
|
|
|
|
2022-11-29 07:54:03 -05:00
|
|
|
return { name: midi.header.name, notes: noteList, loop: false, loopPosition: 0, length: songLength }
|
2022-08-14 05:51:45 -04:00
|
|
|
}
|
|
|
|
|
2022-11-29 07:54:03 -05:00
|
|
|
module.exports = { convertMidi, convertNote, convertPercussionNote }
|