Skip to content

Instantly share code, notes, and snippets.

@iCorv
Created January 20, 2022 12:15
Show Gist options
  • Save iCorv/0b6a77ef07ca6fecd0c9bc4a8aa23b1c to your computer and use it in GitHub Desktop.
Save iCorv/0b6a77ef07ca6fecd0c9bc4a8aa23b1c to your computer and use it in GitHub Desktop.
import os
import pretty_midi
import jams
def jams_to_midi(filepath, q=1):
# q = 1: with pitch bend. q = 0: without pitch bend.
jam = jams.load(filepath)
midi = pretty_midi.PrettyMIDI()
annos = jam.search(namespace='note_midi')
if len(annos) == 0:
annos = jam.search(namespace='pitch_midi')
for anno in annos:
midi_ch = pretty_midi.Instrument(program=25)
for note in anno:
pitch = int(round(note.value))
bend_amount = int(round((note.value - pitch) * 4096))
st = note.time
dur = note.duration
n = pretty_midi.Note(
velocity=100 + np.random.choice(range(-5, 5)),
pitch=pitch, start=st,
end=st + dur
)
pb = pretty_midi.PitchBend(pitch=bend_amount * q, time=st)
midi_ch.notes.append(n)
midi_ch.pitch_bends.append(pb)
if len(midi_ch.notes) != 0:
midi.instruments.append(midi_ch)
return midi
def convert_jams_to_midi(folder, q=1):
files = [name for name in os.listdir(folder) if name.endswith(".jams")]
for filepath in files:
midi_filepath = filepath.split(".")[0]
midi_filepath = os.path.join(folder, midi_filepath + ".mid")
filepath = os.path.join(folder, filepath)
midi = jams_to_midi(filepath, q)
midi.write(midi_filepath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment