Skip to content

Instantly share code, notes, and snippets.

@craffel
Last active May 28, 2018 23:40
Show Gist options
  • Save craffel/50a422f431350f0b3b09 to your computer and use it in GitHub Desktop.
Save craffel/50a422f431350f0b3b09 to your computer and use it in GitHub Desktop.
Faster pretty_midi Fluidsynth method
import tempfile
import subprocess
import os
import pretty_midi
import librosa
def fast_fluidsynth(m, fs):
'''
Faster fluidsynth synthesis using the command-line program
instead of pyfluidsynth.
Parameters
----------
- m : pretty_midi.PrettyMIDI
Pretty MIDI object
- fs : int
Sampling rate
Returns
-------
- midi_audio : np.ndarray
Synthesized audio, sampled at fs
'''
# Write out temp mid file
temp_mid = tempfile.NamedTemporaryFile()
m.write(temp_mid.name)
# Get path to temporary .wav file
temp_wav = tempfile.NamedTemporaryFile()
# Get path to default pretty_midi SF2
sf2_path = os.path.join(os.path.dirname(pretty_midi.__file__),
pretty_midi.DEFAULT_SF2)
# Make system call to fluidsynth
with open(os.devnull, 'w') as devnull:
subprocess.check_output(
['fluidsynth', '-F', temp_wav.name, '-r', str(fs), sf2_path,
temp_mid.name], stderr=devnull)
# Load from temp wav file
audio, _ = librosa.load(temp_wav.name, sr=fs)
# Occasionally, fluidsynth pads a lot of silence on the end, so here we
# crop to the length of the midi object
audio = audio[:int(m.get_end_time() * fs)]
# Close/delete temp files
temp_mid.close()
temp_wav.close()
return audio
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment