|
MacOS下通过HomeBrew安装ffmpeg与timidity实现将midi文件转换为mp3的Python代码
- import os
- import subprocess
- import pickle
- import glob
- from music21 import converter, instrument, note, chord, stream
- def convert_midi_to_mp3():
- """
- 将神经网络生成的 MIDI 文件转成 MP3 文件
- """
- input_file = '1.mid'
- output_file = 'output.mp3'
- if not os.path.exists(input_file):
- raise Exception("MIDI 文件 {} 不在此目录下,请确保此文件被正确生成".format(input_file))
- print('将 {} 转换为 MP3'.format(input_file))
- """
- 用 timidity 生成 mp3 文件
- # 注意:Windows 用户可能需要用其他命令来将 MIDI 文件转为 MP3 文件
- # 注意:Mac 用户貌似 libmp3lame 选项会出错,需要下载编译 libmp3lame,
- # 再重新编译 ffmpeg :http://blog.csdn.net/qinggebuyao/article/details/20933497
- # 不过,Mac 用户直接用自带的 GarageBand(车库乐队)可以直接播放生成的 MIDI 文件,比 ffmpeg 生成的 MP3 音色更好
- """
- command = 'timidity {} -Ow -o - | ffmpeg -i - -acodec libmp3lame -ab 64k {}'.format(input_file, output_file)
- return_code = subprocess.call(command, shell=True)
- if return_code != 0:
- print('转换时出错,请查看出错信息')
- else:
- print('转换完毕. 生成的文件是 {}'.format(output_file))
- convert_midi_to_mp3()
复制代码
|
|