MIDI 本身并不是声音频号,而是声音该用哪种乐器、要以哪个音高、在什么时候、以多长的长度、以多大的力道等数值来演奏的消息。那么在 Linux 操作系统上要如何把 MIDI 文件转成一般的 FLAC、MP3、OGG 等等的音乐文件呢?

安装 FluidSynth

Debian 系的 Linux 发行版可以用以下指令来安装 FluidSynth:

sudo apt install fluidsynth

红帽系的 Linux 发行版可以用以下指令来安装 FluidSynth:

sudo dnf install fluidsynth

使用 FluidSynth

透过 FluidSynth,将 MIDI 文件转成一般音乐文件的指令格式如下:

fluidsynth -T flac -F /path/to/output-flac-file -r 48000 /path/to/sound-font-file /path/to/input-midi-file

fluidsynth 指令的 -r 参数可以设置输出的音频采样频率,通常会使用 44100 或是 48000 赫兹。至于 /path/to/sound-font-file 是 SoundFont 文件的路径,如果您不知道什么是 SoundFont,或是没有 SoundFont 文件,可以参阅这篇文章。

fluidsynth 指令输出的音乐档的音量并没有经过范式,播放出来的声音可能会偏小声。若要做范式处理,可以搭配 FFmpeg 来使用,指令如下:

fluidsynth -T flac -F temp.flac -r 48000 /path/to/sound-font-file /path/to/input-midi-file && ffmpeg -i temp.flac -filter:a "volume=$(ffmpeg -i temp.flac -filter:a volumedetect -f null - 2>&1 | grep max_volume | awk -F " " '{print -$(NF-1) - 0.1}')dB" /path/to/output-audio-file && rm temp.flac

如果想要更深入了解透过 FFmpeg 来进行音量范式的方式,可以参考这篇文章。

以 fluidsynth 转换 MIDI 并范式音量

如果还要在音乐的头、尾再加上一段空白时间,指令如下:

fluidsynth -T flac -F temp.flac -r 48000 /path/to/sound-font-file /path/to/input-midi-file && ffmpeg -f lavfi -t 1 -i anullsrc -i temp.flac -filter_complex "[1:a]volume=$(ffmpeg -i temp.flac -filter:a volumedetect -f null - 2>&1 | grep max_volume | awk -F " " '{print -$(NF-1) - 0.1}')dB[na];[0:a][na][0:a]concat=n=3:v=0:a=1[outa]" -map "[outa]" /path/to/output-audio-file && rm temp.flac

以上指令中,ffmpeg 的 -f lavfi -t 1 -i anullsrc 参数可以输入一段时长 1 秒的空白音频。

不过使用这样的方式产生出来的音乐档会有一个很明显的缺点,那就是声音在结尾的时候会直接结束,缺少残响与淡出,还会有喀答声(click)产生,目前还不知道这要怎么解决比较好。