You can play musical notes from a Python program using FluidSynth, a free real-time software synthesizer.
1. Go to the FluidSynth
releases page and
download the latest 64-bit release for Windows (e.g.
fluidsynth-2.1.0-win64.zip). Extract this zip file into some
directory, e.g. c:\Users\
me
\install
.
2. Add the fluidsynth-x64\bin
subdirectory to your
PATH. To do this, click in the search box on the task bar, run the
command 'Edit the system environment variables', click 'Environment
Variables…', select Path
in the 'User variables' section, click 'Edit…', click New, then
enter the path of the bin subdirectory, e.g.
c:\Users\
me
\install\fluidsynth-x64\bin
.
3. FluidSynth needs a file FluidR3_GM.sf2 that contains waveforms for various musical instruments. You can download this file from the page The Fluid Release 3 General-MIDI Soundfont. On that page, click the link 'Download FluidR3_GM Soundfont'. Save the file in some directory.
4. Play a MIDI file to verify that FluidSynth is working correctly. For example, here is a MIDI file book1-prelude01.mid containing a prelude by Bach. Save it to the directory where you saved the soundfont file in the previous step. Now open a command prompt, navigate to that directory, and run
fluidsynth FluidR3_GM.sf2 book1-prelude01.mid
You should hear the prelude playing. If not, something is not installed correctly, and you should fix the problem before preceding to the next step.
The soundfont file you saved contains waveforms for dozens of instruments that FluidSynth can synthesize in real time. To hear its impressive organ sound, download this famous Bach toccata and fugue and play it with FluidSynth. (You can find many more MIDI sound files at this Classical MIDI page.)
5. Now you'll need to install pyfluidsynth, which lets you access FluidSynth from Python:
pip install pyfluidsynth
6. The following Python program will play a chord for a few seconds:
import time import fluidsynth fs = fluidsynth.Synth() fs.start(driver = 'dsound') # use DirectSound driver sfid = fs.sfload(r'c:\users\me\mydir\FluidR3_GM.sf2') # replace path as needed fs.program_select(0, sfid, 0, 0) fs.noteon(0, 60, 30) fs.noteon(0, 67, 30) fs.noteon(0, 76, 30) time.sleep(3.0) fs.noteoff(0, 60) fs.noteoff(0, 67) fs.noteoff(0, 76) time.sleep(1.0) fs.delete()
Save this program to a file chord.py
, and replace the
path in the second commented line above with the full path to the
FluidR3_GM.sf2 file on your machine. Now run the program. You should
hear a chord play.
There is some (minimal) documentation about the pyfluidsynth API on the pyfluidsynth GitHub page. If you have questions about the API or using pyfluidsynth, feel free to ask me.