### router_begin example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-router.md Example call to router_begin with the "cc" type to start building a control change rule. ```python fs.router_begin("cc") ``` -------------------------------- ### Complete MIDI routing pipeline example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-router.md Complete routing pipeline example: creates a Synth, starts it, builds a note rule that transposes all notes up 12 semitones on channel 0, then clears and restores default rules. Demonstrates the full begin-configure-end sequence. ```python import fluidsynth fs = fluidsynth.Synth() fs.start() # Route: transpose all notes up 12 semitones, keep them on channel 0 fs.router_begin("note") fs.router_chan(0, 0, 1.0, 0) fs.router_par1(0, 127, 1.0, 12) # all velocity values pass through, key += 12 fs.router_par2(0, 127, 1.0, 12) # key transposed +12 fs.router_end() fs.router_clear() # remove all rules again fs.router_default() # restore FluidSynth's default rules ``` -------------------------------- ### Basic start() call Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Basic call to start the audio output driver with default drivers for the platform. ```python import fluidsynth fs = fluidsynth.Synth() fs.start() # uses default drivers for the platform ``` -------------------------------- ### start method signature Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Signature of the start method. Starts the audio output driver (and MIDI driver/router) in a separate background thread. If never called, use get_samples() to pull audio manually. ```python def start(self, driver=None, device=None, midi_driver=None, midi_router=None): ``` -------------------------------- ### process usage example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/sequencer.md Example usage of the process method: advances the sequencer by 50 milliseconds. ```python seq.process(50) # advance 50 ms ``` -------------------------------- ### sfpreset_name example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Gets the preset name for the given SoundFont ID, bank 0, and preset 0, then prints it. ```python name = fs.sfpreset_name(sfid, 0, 0) print(name) ``` -------------------------------- ### Basic delete call Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Basic call example for the delete method. Creates a Synth, starts it, plays music, then calls delete to free resources. ```python fs = fluidsynth.Synth() fs.start() # ... play music ... fs.delete() ``` -------------------------------- ### program_info example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Retrieves the active soundfont, bank, and program for channel 0. ```python sfontid, banknum, presetnum = fs.program_info(0) ``` -------------------------------- ### Install pre-release pyfluidsynth from source Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Clone the repository, navigate to the repository directory, and run this command to install the pre-release version in editable mode. ```bash pip install --editable . ``` -------------------------------- ### router_begin Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-router.md Starts building a new MIDI router rule of the specified type. ```APIDOC ## router_begin(type) ### Description Starts building a new MIDI router rule of the given type. Frees any previously built but not yet added rule. ### Method router_begin ### Parameters - **type** (str) - Required - One of "note", "cc", "prog", "pbend", "cpress", "kpress". ### Returns None ### Example ```python fs.router_begin("cc") ``` ``` -------------------------------- ### Synth.start Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Documentation for the `start` method of the `Synth` class in the pyfluidsynth library. ```APIDOC ## `start` ```python def start(self, driver=None, device=None, midi_driver=None, midi_router=None): ``` ### Description Starts the audio output driver (and MIDI driver/router) in a separate background thread. If you never call this, use `get_samples()` to pull audio manually. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `driver` | str | no | `None` | Audio driver name. Falls back to the current `audio.driver` setting. Allowed values and platform defaults are defined by FluidSynth (see http://www.fluidsynth.org/api/fluidsettings.xml). | | `device` | str | no | `None` | Audio device, falls back to the `audio..device` setting. | | `midi_driver` | str | no | `None` | MIDI driver, falls back to the `midi.driver` setting. | | `midi_router` | callable | no | `None` | External MIDI event handler. When given, it is wrapped in a `CFUNCTYPE(c_int, c_void_p, c_void_p)` and used as the MIDI driver handler instead of FluidSynth's built-in router handler; the wrapped callback is stored in `self.custom_router_callback`. When `None`, `fluid_midi_router_handle_midi_event` is used. | ### Behavior Sets `audio.driver`, `audio..device`, and `midi.driver` settings; creates the audio driver; creates a MIDI router (`new_fluid_midi_router`) with `fluid_synth_handle_midi_event` as handler; then installs a command handler (`new_fluid_cmd_handler(self.synth, self.router)`) when the FluidSynth 2.x symbol is present, otherwise falls back to `fluid_synth_set_midi_router(self.synth, self.router)`; finally creates the MIDI driver. ### Returns `FLUID_OK` (int `0`) unconditionally. ### Example — basic call ```python import fluidsynth fs = fluidsynth.Synth() fs.start() # uses default drivers for the platform ``` ### Example — explicit drivers and custom MIDI router callback ```python def my_midi_handler(data, event): # data == fs.router, event is a low-level fluid_midi_event_t print('midi event received:', fs.midi_event_get_type(event)) return fluidsynth.FLUID_OK fs = fluidsynth.Synth() fs.start(driver="alsa", midi_driver="alsa_seq", midi_router=my_midi_handler) ``` ``` -------------------------------- ### channel_info example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Retrieves channel info for channel 0 and prints the preset name. ```python sfid, bank, prog, name = fs.channel_info(0) print(name) ``` -------------------------------- ### Example: using raw_audio_string Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/module-functions.md Example usage of raw_audio_string to convert samples from get_samples into a bytes string and write it to a stream. ```python samples = fs.get_samples(44100) data = fluidsynth.raw_audio_string(samples) stream.write(data) ``` -------------------------------- ### Example: using fluid_synth_write_s16_stereo Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/module-functions.md Example usage of fluid_synth_write_s16_stereo to generate 2048 sample frames of stereo audio after triggering a note, printing the array size (4096 for stereo). ```python import fluidsynth fs = fluidsynth.Synth() fs.noteon(0, 60, 90) arr = fluidsynth.fluid_synth_write_s16_stereo(fs.synth, 2048) print(arr.size) # 4096 (stereo) ``` -------------------------------- ### Synth.start Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/configuration.md Starts the synthesizer with optional audio and MIDI driver configurations, including an external MIDI event handler. ```APIDOC ## Synth.start(driver=None, device=None, midi_driver=None, midi_router=None) ### Description Starts the synthesizer with optional audio and MIDI driver configurations. If parameters are not provided, it falls back to the current FluidSynth settings. The midi_router parameter allows setting an external MIDI event handler. ### Method start ### Parameters #### Parameters - **driver** (str) - Optional, default `None` - Audio driver name; falls back to the current `audio.driver` setting. Platform defaults defined by FluidSynth. - **device** (str) - Optional, default `None` - Audio device; falls back to `audio..device`. - **midi_driver** (str) - Optional, default `None` - MIDI driver; falls back to `midi.driver`. - **midi_router** (callable) - Optional, default `None` - External MIDI event handler. When set, wrapped in `CFUNCTYPE(c_int, c_void_p, c_void_p)` and used as the MIDI driver handler; `Synth.custom_router_callback` stores the wrapper. ### Request Example ```python synth.start(driver='alsa', device='default', midi_driver='alsa_seq') ``` ### Response #### Success Response No return value. The synthesizer is started with the specified configuration. ``` -------------------------------- ### Basic Synth construction with defaults Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Creates a Synth with default settings (gain=0.2, samplerate=44100, channels=256) and then deletes it. Use this as the minimal setup for a synthesizer instance. ```python import fluidsynth fs = fluidsynth.Synth() # gain=0.2, samplerate=44100, channels=256 fs.delete() ``` -------------------------------- ### program_select usage example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Example usage of program_select: loads a SoundFont, selects a program on channel 0, and triggers a note-on. The comment shows the argument order: track, sfid, bank, preset. ```python sfid = fs.sfload("example.sf2") fs.program_select(0, sfid, 0, 0) # track, sfid, bank, preset fs.noteon(0, 60, 80) ``` -------------------------------- ### cc usage examples Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Example calls to cc. Sends a MIDI control change. Returns the fluid_synth_cc status int. ```python fs.cc(0, 7, 100) # channel volume fs.cc(0, 64, 127) # sustain on ``` -------------------------------- ### sfload basic call example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Loads a SoundFont and checks for failure by comparing the returned ID to FLUID_FAILED. No exception is raised on failure. ```python fs = fluidsynth.Synth() sfid = fs.sfload("example.sf2") if sfid == fluidsynth.FLUID_FAILED: print("SoundFont failed to load") ``` -------------------------------- ### set_reverb usage example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-effects.md Example usage of set_reverb. The second call only updates the level parameter because the others are left at their negative defaults. ```python fs.set_reverb(roomsize=0.5, damping=0.4, width=20.0, level=0.8) fs.set_reverb(level=0.9) # only level is updated ``` -------------------------------- ### start() with explicit drivers and custom MIDI router Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Explicit drivers and a custom MIDI router callback. The callback receives the router as data and a low-level fluid_midi_event_t as event; it must return FLUID_OK. ```python def my_midi_handler(data, event): # data == fs.router, event is a low-level fluid_midi_event_t print('midi event received:', fs.midi_event_get_type(event)) return fluidsynth.FLUID_OK fs = fluidsynth.Synth() fs.start(driver="alsa", midi_driver="alsa_seq", midi_router=my_midi_handler) ``` -------------------------------- ### Install pyfluidsynth with pip Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Install the latest official release of pyfluidsynth using pip. Use the second command to also install PyAudio support. ```bash pip install pyfluidsynth ``` ```bash pip install "pyfluidsynth[pyaudio]" ``` -------------------------------- ### note method usage example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/sequencer.md Example of scheduling notes using the note method. The first call uses absolute timing (now), the second uses relative timing (250 ticks from now). Both specify a destination synth_id. ```python now = seq.get_tick() seq.note(now, 0, 60, 100, 500, dest=synth_id) # absolute seq.note(250, 0, 64, 100, 500, dest=synth_id, absolute=False) # relative ``` -------------------------------- ### program_info Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Gets the active soundfont, bank, and program on a channel. ```APIDOC ## program_info ### Description Gets the active soundfont, bank, and program on a channel. Uses `fluid_synth_get_program` when available; otherwise derives the values from `channel_info()`. ### Method program_info ### Endpoint `program_info(self, chan)` ### Parameters #### Path Parameters - **chan** (int) - Required - MIDI channel. ### Request Example ```python sfontid, banknum, presetnum = fs.program_info(0) ``` ### Response #### Success Response - **tuple** - `(sfontid, banknum, presetnum)` of ints. #### Response Example ```python sfontid, banknum, presetnum = fs.program_info(0) ``` ``` -------------------------------- ### Build pitch bend rule example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-router.md Example of building a pitch bend rule: sets parameter 1 range to 0-16383 with no scaling or offset, then ends the rule. ```python fs.router_begin("pbend") fs.router_par1(0, 16383, 1.0, 0) fs.router_end() ``` -------------------------------- ### router_begin method signature Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-router.md Starts building a new MIDI router rule of the given type. Frees any previously built but not yet added rule. The type must be one of "note", "cc", "prog", "pbend", "cpress", or "kpress". ```python def router_begin(self, type): ``` -------------------------------- ### sfload with MIDI preset update example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Loads a SoundFont with update_midi_preset set to 1, triggering a remap of MIDI programs to the new SoundFont's presets. ```python sfid = fs.sfload("example.sf2", update_midi_preset=1) ``` -------------------------------- ### MIDI event introspection example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Example of inspecting an incoming MIDI event from a router/sequencer callback. Checks if the event type is note on (0x90) and prints the key and velocity. Returns fluidsynth.FLUID_OK. ```python def midi_handler(data, event): fs = data if fs.midi_event_get_type(event) == 0x90: # 0x90 = note on (MIDI status byte) print(fs.midi_event_get_key(event), fs.midi_event_get_velocity(event)) return fluidsynth.FLUID_OK ``` -------------------------------- ### Advanced Synth construction with arbitrary FluidSynth settings Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Creates a Synth with custom gain, samplerate, and channels, and passes arbitrary FluidSynth settings via **kwargs. Dotted setting names must be passed as a mapping. The example prints the resulting sample-rate setting (48000.0) and then deletes the instance. ```python import fluidsynth fs = fluidsynth.Synth( gain=0.5, samplerate=48000, channels=16, # any FluidSynth setting name works via **kwargs # (dotted names must be passed as a mapping) **{"synth.polyphony": 64, "audio.period-size": 512, "audio.periods": 4}, ) print(fs.get_setting('synth.sample-rate')) # 48000.0 fs.delete() ``` -------------------------------- ### Schedule a Note with Absolute Timing using seq.get_tick() Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Schedules the same note as the relative example but using absolute track positions in ticks. The default for absolute is True, so you must provide absolute tick positions. This snippet gets the current tick and adds 500 to schedule the note. ```python current_time = seq.get_tick() seq.note_on(current_time + 500, 0, 60, 80, dest=synth_id) ``` -------------------------------- ### Use individual reverb and chorus setters Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-effects.md Example calls to the individual setters for reverb roomsize and chorus voice count. ```python fs.set_reverb_roomsize(0.6) fs.set_chorus_nr(4) ``` -------------------------------- ### Configure pyfluidsynth Synth with settings, drivers, and sequencer Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/configuration.md Shows the full configuration surface of the pyfluidsynth Synth class: constructor options, arbitrary FluidSynth settings passed as a mapping, reading settings back, driver selection at start, and manual sequencer configuration. Note that dotted setting names must be passed as a mapping, and get_setting('audio.driver') returns the platform default or None before start. ```python import fluidsynth # Constructor options + arbitrary FluidSynth settings # (dotted setting names must be passed as a mapping) fs = fluidsynth.Synth( gain=0.3, samplerate=48000, channels=16, **{"synth.polyphony": 96, "synth.reverb.active": 0}, ) # Read back settings fs.get_setting('synth.polyphony') # 96 fs.get_setting('audio.driver') # platform default, or None pre-start # Driver selection at start fs.start(driver="pulseaudio", midi_driver="alsa_seq") # Manual sequencer configuration seq = fluidsynth.Sequencer(time_scale=480, use_system_timer=False) ``` -------------------------------- ### Configure note rule with channel and velocity mapping Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-router.md Example showing how to configure a note rule: maps all notes to channel 1 and clamps velocity to 60-100. Uses router_begin, router_chan, router_par1, and router_end. ```python # Map all notes to channel 1, velocity 60-100 fs.router_begin("note") fs.router_chan(0, 127, 1.0, 1) fs.router_par1(60, 100, 1.0, 0) fs.router_end() ``` -------------------------------- ### channel_info Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Gets the soundfont, bank, program, and preset name of a channel. ```APIDOC ## channel_info ### Description Gets the soundfont, bank, program, and preset name of a channel. Uses `fluid_synth_get_channel_info` when available (FluidSynth ≥ 2.2), otherwise falls back to `program_info()` + `sfpreset_name()`. ### Method channel_info ### Endpoint `channel_info(self, chan)` ### Parameters #### Path Parameters - **chan** (int) - Required - MIDI channel. ### Request Example ```python sfid, bank, prog, name = fs.channel_info(0) print(name) ``` ### Response #### Success Response - **tuple** - `(sfont_id, bank, program, name)` where `sfont_id`, `bank`, `program` are int and `name` is the preset name. In the primary path `name` is the content of the C `c_char*32` field; in the fallback path `name` is the str returned by `sfpreset_name` (or `None`). #### Response Example ```python sfid, bank, prog, name = fs.channel_info(0) print(name) ``` ``` -------------------------------- ### timer usage example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/sequencer.md Example usage of the timer method: schedules a timer event 2000 ticks from the current tick, targeting a callback ID. ```python current_time = seq.get_tick() seq.timer(current_time + 2000, dest=callback_id) ``` -------------------------------- ### noteon method signature Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Starts a note on a given track with a MIDI note number and velocity. ```python noteon(track, midinum, velocity) ``` -------------------------------- ### Pull-mode audio with get_samples and PyAudio Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Pull-mode audio example using get_samples with PyAudio. Generates 1 second of audio (44100 frames, 88200 int16 values), converts to bytes with raw_audio_string, and writes to a PyAudio stream. Requires a SoundFont file (example.sf2) and the pyaudio library. ```python import numpy import pyaudio import fluidsynth fs = fluidsynth.Synth() sfid = fs.sfload("example.sf2") fs.program_select(0, sfid, 0, 0) fs.noteon(0, 60, 100) samples = fs.get_samples(44100) # 1 second, 88200 int16 values data = fluidsynth.raw_audio_string(samples) # convert to bytes for the soundcard pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels=2, rate=44100, output=True) stream.write(data) fs.noteoff(0, 60) fs.delete() ``` -------------------------------- ### Play a chord with pyfluidsynth Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Creates a Synth object, starts audio output in a separate thread, loads a SoundFont, selects a program, plays a chord for one second, then stops it and deletes the synth. ```python import time import fluidsynth fs = fluidsynth.Synth() fs.start() sfid = fs.sfload("example.sf2") fs.program_select(0, sfid, 0, 0) fs.noteon(0, 60, 30) fs.noteon(0, 67, 30) fs.noteon(0, 76, 30) time.sleep(1.0) fs.noteoff(0, 60) fs.noteoff(0, 67) fs.noteoff(0, 76) time.sleep(1.0) fs.delete() ``` -------------------------------- ### sfunload example Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Unloads a SoundFont using its ID obtained from sfload. ```python fs.sfunload(sfid) ``` -------------------------------- ### Change program with program_change Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Changes the program (preset) on a channel using program_change. The example sets channel 0 to program 5. ```python fs.program_change(0, 5) ``` -------------------------------- ### Set chorus with specific values Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-effects.md Example call to set_chorus using keyword arguments for all chorus parameters. The values fall within the documented ranges. ```python fs.set_chorus(nr=3, level=2.0, speed=1.5, depth=8.0, type=0) ``` -------------------------------- ### Concatenating get_samples buffers Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Example of concatenating buffers from get_samples. Appends two 1-second buffers to create 2 seconds of audio. Requires numpy. ```python import numpy import fluidsynth fs = fluidsynth.Synth() out = numpy.append(fs.get_samples(44100), fs.get_samples(44100)) # 2 s of audio fs.delete() ``` -------------------------------- ### Select bank with bank_select Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Chooses a SoundFont bank on a channel using bank_select. The example selects bank 5 on channel 0. ```python fs.bank_select(0, 5) ``` -------------------------------- ### program_info method signature Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Defines the program_info method that gets the active soundfont, bank, and program on a channel. Uses fluid_synth_get_program when available, otherwise derives values from channel_info(). ```python def program_info(self, chan): ``` -------------------------------- ### channel_info method signature Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Defines the channel_info method that gets the soundfont, bank, program, and preset name of a channel. Uses fluid_synth_get_channel_info when available, otherwise falls back to program_info() and sfpreset_name(). ```python def channel_info(self, chan): ``` -------------------------------- ### Register a Callback Client with sequencer.register_client() Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Registers a custom callback function to be called at certain ticks. The callback receives low-level event and seq objects, not Python objects. The example schedules the callback to fire at current_time + 2000 ticks. ```python def seq_callback(time, event, seq, data): print('callback called!') callback_id = sequencer.register_client("myCallback", seq_callback) sequencer.timer(current_time + 2000, dest=callback_id) ``` -------------------------------- ### Schedule a Note with Relative Timing using seq.note_on() Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Schedules a note-on event using relative timing: the event is placed the specified time from the current position. The example schedules a note at time=500 ticks from now, on channel 0, key 60, velocity 80, targeting the registered synthesizer. ```python seq.note_on(time=500, absolute=False, channel=0, key=60, velocity=80, dest=synth_id) ``` -------------------------------- ### pitch_bend usage examples Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Example calls to pitch_bend. The value is clamped to the MIDI pitch-bend range before dispatch. Returns the fluid_synth_pitch_bend status int. ```python fs.pitch_bend(0, 0) # neutral fs.pitch_bend(0, -2048) # one semitone down fs.pitch_bend(0, 8191) # maximum upward bend (clamped) ``` -------------------------------- ### Generate chord and play with PyAudio Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Generates a chord using get_samples, appends the samples, converts them to a raw audio string, and plays them with PyAudio. Includes a script header for uv run with dependencies. ```python #!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.10" # dependencies = [ # "numpy", # "pyaudio", # "pyfluidsynth", # ] # /// import time import numpy import pyaudio import fluidsynth pa = pyaudio.PyAudio() strm = pa.open( format = pyaudio.paInt16, channels = 2, rate = 44100, output = True) s = [] fl = fluidsynth.Synth() # Initial silence is 1 second s = numpy.append(s, fl.get_samples(44100 * 1)) sfid = fl.sfload("example.sf2") fl.program_select(0, sfid, 0, 0) fl.noteon(0, 60, 30) fl.noteon(0, 67, 30) fl.noteon(0, 76, 30) # Chord is held for 2 seconds s = numpy.append(s, fl.get_samples(44100 * 2)) fl.noteoff(0, 60) fl.noteoff(0, 67) fl.noteoff(0, 76) # Decay of chord is held for 1 second s = numpy.append(s, fl.get_samples(44100 * 1)) fl.delete() samps = fluidsynth.raw_audio_string(s) print(len(samps)) print('Starting playback') strm.write(samps) ``` -------------------------------- ### Play a MIDI file with play_midi_file Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-player.md Loads a SoundFont, plays a MIDI file for 20 seconds, then stops playback. Requires a prior `import fluidsynth` and `import time`. ```python fs = fluidsynth.Synth() sfid = fs.sfload("example.sf2") fs.play_midi_file("song.mid") time.sleep(20) fs.play_midi_stop() ``` -------------------------------- ### Create a Sequencer with fluidsynth.Sequencer() Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Creates a sequencer that advances at 1000 ticks per second by default, using the system clock as the time source. Pass time_scale to change the rate, or use_system_timer=False to manually advance it with sequencer.process. ```python import fluidsynth seq = fluidsynth.Sequencer() ``` -------------------------------- ### program_select Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Selects a program — the standard way to choose an instrument before playing. ```APIDOC ## program_select ### Description Selects a program — the standard way to choose an instrument before playing. ### Method program_select ### Endpoint program_select(self, chan, sfid, bank, preset) ### Parameters #### Path Parameters - **chan** (int) - Required - MIDI channel. - **sfid** (int) - Required - SoundFont ID from `sfload`. - **bank** (int) - Required - Bank number. - **preset** (int) - Required - Preset number. ### Request Example ```python sfid = fs.sfload("example.sf2") fs.program_select(0, sfid, 0, 0) # track, sfid, bank, preset fs.noteon(0, 60, 80) ``` ### Response #### Success Response - **Returns:** the `fluid_synth_program_select` status int. ``` -------------------------------- ### Synth.__init__ Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/configuration.md Constructor for the Synth class, allowing configuration of gain, sample rate, MIDI channels, and additional FluidSynth settings. ```APIDOC ## Synth.__init__(gain=0.2, samplerate=44100, channels=256, **kwargs) ### Description Initializes a Synth object with configurable gain, sample rate, MIDI channel count, and additional FluidSynth settings. The gain, samplerate, and channels parameters are stored via the settings API, and any additional keyword arguments are passed directly to the settings API. ### Method Constructor ### Parameters #### Constructor Parameters - **gain** (float) - Optional, default `0.2` - Audio output scale factor; lower values are quieter and allow more simultaneous notes. Stored via `setting('synth.gain', gain)`. - **samplerate** (int/float) - Optional, default `44100` - Output sample rate in Hz. Stored via `setting('synth.sample-rate', float(samplerate))`. - **channels** (int) - Optional, default `256` - MIDI channel count. Stored via `setting('synth.midi-channels', channels)`. - **kwargs** (any) - Optional - Any additional FluidSynth setting, passed straight to `setting(opt, val)`. Keys must be valid setting names, e.g. `synth.polyphony`, `audio.period-size`. ### Request Example ```python synth = Synth(gain=0.5, samplerate=48000, channels=128, synth.polyphony=64) ``` ### Response #### Success Response No return value. The Synth object is initialized with the specified settings. ``` -------------------------------- ### Read controller value with get_cc Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Reads the current value of a controller on a channel using get_cc. The example prints the returned controller value. ```python value = fs.get_cc(0, 7) print(value) ``` -------------------------------- ### Get active voice count after note-on Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Triggers a note-on and then prints the number of active voices. The comment indicates the expected output is 1. ```python fs.noteon(0, 60, 100) print(fs.get_active_voice_count()) # 1 ``` -------------------------------- ### Create manually clocked Sequencer with process() Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/sequencer.md Initializes a Sequencer with a custom time scale (480 ticks/sec) and disables the system timer, requiring manual advancement via process(). The loop advances the sequencer by 10 ms of sequencer time each iteration. ```python seq = fluidsynth.Sequencer(time_scale=480, use_system_timer=False) while True: seq.process(10) # advance by 10 ms of sequencer time ``` -------------------------------- ### Full scheduling flow with Sequencer Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/sequencer.md Full scheduling flow: creates a synthesizer, loads a SoundFont, registers it with a sequencer, schedules note on/off events, then deletes both the sequencer and synthesizer. Requires an `example.sf2` file and sleeps 2 seconds to allow playback. ```python import time import fluidsynth fs = fluidsynth.Synth() fs.start() sfid = fs.sfload("example.sf2") fs.program_select(0, sfid, 0, 0) seq = fluidsynth.Sequencer() synth_id = seq.register_fluidsynth(fs) now = seq.get_tick() seq.note_on(now, 0, 60, 100, dest=synth_id) seq.note_off(now + 1000, 0, 60, dest=synth_id) time.sleep(2) seq.delete() fs.delete() ``` -------------------------------- ### get_setting method basic call Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Basic call to the get_setting method, showing how it returns different types and None for non-existent settings. ```python fs = fluidsynth.Synth() print(fs.get_setting('synth.sample-rate')) # 44100.0 print(fs.get_setting('synth.gain')) # 0.2 print(fs.get_setting('no.such.setting')) # None ``` -------------------------------- ### FLUID_PLAYER_READY/PLAYING/STOPPING/DONE Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/index.md Module-level integer constants for player states. ```APIDOC ## FLUID_PLAYER_READY/PLAYING/STOPPING/DONE ### Description Integer constants representing the states of the MIDI player: ready, playing, stopping, and done. ``` -------------------------------- ### Set playback tempo with player_set_tempo Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-player.md Sets the tempo of the current player to 25% faster using `FLUID_PLAYER_TEMPO_EXTERNAL_BPM`. Requires a prior `play_midi_file` call; otherwise `self.player` does not exist. ```python fs.play_midi_file("song.mid") fs.player_set_tempo(fluidsynth.FLUID_PLAYER_TEMPO_EXTERNAL_BPM, 1.25) # 25% faster ``` -------------------------------- ### sfload Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-soundfonts.md Loads a SoundFont file and returns its ID. ```APIDOC ## sfload ### Description Loads a SoundFont file and returns its ID. Optionally remaps MIDI programs to the new SoundFont's presets. ### Method sfload ### Endpoint `sfload(self, filename, update_midi_preset=0)` ### Parameters #### Path Parameters - **filename** (str) - Required - Path to a `.sf2` SoundFont file. Encoded to bytes and passed to `fluid_synth_sfload`. - **update_midi_preset** (int) - Optional - Default: `0`. When non-zero, MIDI programs are remapped to the new SoundFont's presets. ### Request Example ```python fs = fluidsynth.Synth() sfid = fs.sfload("example.sf2") if sfid == fluidsynth.FLUID_FAILED: print("SoundFont failed to load") ``` ### Response #### Success Response - **int** - The SoundFont ID on success, or `FLUID_FAILED` (`-1`) if the file could not be loaded. No exception is raised on failure. #### Response Example ```python sfid = fs.sfload("example.sf2", update_midi_preset=1) ``` ``` -------------------------------- ### Create default self-advancing Sequencer Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/sequencer.md Initializes a Sequencer with default settings: 1000 ticks per second and system timer enabled. The sequencer advances itself from the system clock. ```python import fluidsynth seq = fluidsynth.Sequencer() # default: 1000 ticks/sec, advanced by the system clock ``` -------------------------------- ### get_samples method signature Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Generates the next chunk of audio samples. The length parameter is the number of audio samples; the return value is a Numpy array of samples, with length 2 * len for stereo output. ```python get_samples(len) ``` -------------------------------- ### program_select method signature Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Selects a bank and preset for a given track and SoundFont. Parameters: track, soundfontid, banknum, presetnum. ```python program_select(track, soundfontid, banknum, presetnum) ``` -------------------------------- ### Sequencer.__init__ Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/configuration.md Constructor for the Sequencer class, allowing configuration of time scale and timer behavior. ```APIDOC ## Sequencer.__init__(time_scale=1000, use_system_timer=True) ### Description Initializes a Sequencer object with configurable time scale and timer behavior. The time_scale parameter sets the number of sequencer ticks per second, and use_system_timer determines whether the sequencer advances automatically or requires manual processing. ### Method Constructor ### Parameters #### Constructor Parameters - **time_scale** (float) - Optional, default `1000` - Sequencer ticks per second. Applied via `fluid_sequencer_set_time_scale`. - **use_system_timer** (bool) - Optional, default `True` - `True`: sequencer advances itself from the system clock. `False`: you must call `Sequencer.process(msec)` manually. ### Request Example ```python seq = Sequencer(time_scale=500, use_system_timer=False) ``` ### Response #### Success Response No return value. The Sequencer object is initialized with the specified settings. ``` -------------------------------- ### FLUIDSETTING_EXISTS Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/index.md Module-level integer constant for setting existence. ```APIDOC ## FLUIDSETTING_EXISTS ### Description Integer constant indicating that a setting already exists. ``` -------------------------------- ### FluidSynth Settings API and Environment Variables Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/configuration.md Documentation for the FluidSynth settings API and environment variables in pyfluidsynth. ```APIDOC ## Synth.setting(opt, val) ### Description Sets a FluidSynth setting on the synthesizer. The value is type-smart: strings are encoded to bytes, integers are passed as int, and floats are wrapped in c_double. ### Method N/A (Python method) ### Endpoint Synth.setting(opt, val) ### Parameters - **opt** (str) - Required - The name of the FluidSynth setting to set. - **val** (str, bytes, int, or float) - Required - The value to set. The C call used depends on the Python type: str/bytes -> fluid_settings_setstr, int -> fluid_settings_setint, float -> fluid_settings_setnum. ### Request Example ```python synth.setting('synth.gain', 0.5) ``` ### Response No return value. ## Synth.get_setting(opt) ### Description Retrieves a FluidSynth setting value. It tries integer, string (32-byte buffer), then numeric lookups and returns int, str, or rounded float. A lookup only counts when the C call returns FLUIDSETTING_EXISTS. ### Method N/A (Python method) ### Endpoint Synth.get_setting(opt) ### Parameters - **opt** (str) - Required - The name of the FluidSynth setting to retrieve. ### Request Example ```python value = synth.get_setting('synth.gain') ``` ### Response Returns the setting value as int, str, or float. ## Synth.midi2audio(audiofile) ### Description Converts MIDI to audio, writing the result to the specified audio file. It relies on the audio.file.type and related settings that FluidSynth defaults provide. ### Method N/A (Python method) ### Endpoint Synth.midi2audio(audiofile) ### Parameters - **audiofile** (str) - Required - The path to the output audio file. ### Request Example ```python synth.midi2audio('output.wav') ``` ### Response No return value. ## Environment Variables ### Description Environment variables that affect the behavior of the pyfluidsynth module. ### Variables - **CI** - When truthy, find_libfluidsynth prints the location of each named library found. - **HOMEBREW_PREFIX** - If set and /lib/libfluidsynth.dylib exists, that path is returned (macOS Apple-silicon workaround). - **PATH** - On Windows, if C:\tools\fluidsynth\bin exists, it is appended to PATH at import time. ``` -------------------------------- ### Sequencer.__init__ Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/sequencer.md Constructor for the Sequencer class, which schedules MIDI events at tick positions. It creates a new FluidSynth sequencer and sets its time scale, with options for automatic or manual advancement. ```APIDOC ## `Sequencer.__init__` ### Description Creates a new sequencer (`new_fluid_sequencer2`) and sets its time scale. The sequencer schedules MIDI events at tick positions, advancing itself from the system clock by default or manually via `process()`. ### Method Constructor ### Signature ```python def __init__(self, time_scale=1000, use_system_timer=True): ``` ### Parameters - **time_scale** (float) - Optional - Default: `1000` - Ticks per second. - **use_system_timer** (bool) - Optional - Default: `True` - Whether the sequencer advances by itself using the system clock. `False` means you must advance it manually with `process()`. ### Returns A new `Sequencer` (no explicit return). `self.client_callbacks` is initialized to `[]` and keeps registered Python callbacks alive. ### Example — default (self-advancing) sequencer ```python import fluidsynth seq = fluidsynth.Sequencer() # default: 1000 ticks/sec, advanced by the system clock ``` ### Example — manually clocked sequencer ```python seq = fluidsynth.Sequencer(time_scale=480, use_system_timer=False) while True: seq.process(10) # advance by 10 ms of sequencer time ``` ``` -------------------------------- ### Convert MIDI to audio with midi2audio Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-player.md Renders a MIDI file to an audio file offline. The output file defaults to `output.wav` if not specified. ```python fs = fluidsynth.Synth() sfid = fs.sfload("example.sf2") fs.midi2audio("song.mid", "song.wav") ``` -------------------------------- ### Dump tuning data with tuning_dump Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-player.md Retrieves microtuning offsets for a given bank and program. Returns a sequence of 128 floats representing cents offset for each MIDI note (0.0 = standard tuning). ```python tuning = fs.tuning_dump(0, 0) print(tuning[60]) # cents offset of middle C ``` -------------------------------- ### program_change Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Changes the program (preset) on a channel. ```APIDOC ## program_change ### Description Changes the program (preset) on a channel. ### Method N/A (Python method) ### Endpoint `Synth.program_change(chan, prg)` ### Parameters - `chan` (int) - Required - MIDI channel. - `prg` (int) - Required - Program number. ### Returns int - the `fluid_synth_program_change` status int. ### Example ```python fs.program_change(0, 5) ``` ``` -------------------------------- ### Register a Synthesizer with seq.register_fluidsynth(fs) Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/README.md Registers a fluidsynth.Synth() instance with the sequencer so it can receive MIDI events. The returned synth_id must be kept and used as the target for scheduled events. ```python fs = fluidsynth.Synth() # init and start the synthesizer as described above… synth_id = seq.register_fluidsynth(fs) ``` -------------------------------- ### Use modulator constants with Modulator Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/module-functions.md Creates a Modulator object and sets its first source using the FLUID_MOD_PITCHWHEEL constant combined with FLUID_MOD_BIPOLAR and FLUID_MOD_LINEAR flags. This demonstrates how to use the modulator constants in practice. ```python mod = fluidsynth.Modulator() mod.set_source1(fluidsynth.FLUID_MOD_PITCHWHEEL, fluidsynth.FLUID_MOD_BIPOLAR | fluidsynth.FLUID_MOD_LINEAR) ``` -------------------------------- ### bank_select Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Chooses a SoundFont bank on a channel. ```APIDOC ## bank_select ### Description Chooses a SoundFont bank on a channel. ### Method N/A (Python method) ### Endpoint `Synth.bank_select(chan, bank)` ### Parameters - `chan` (int) - Required - MIDI channel. - `bank` (int) - Required - Bank number. ### Returns int - the `fluid_synth_bank_select` status int. ### Example ```python fs.bank_select(0, 5) ``` ``` -------------------------------- ### setting method basic call Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth.md Basic call to the setting method, showing how different value types map to the underlying C API functions. ```python fs.setting('synth.gain', 0.7) # float -> setnum fs.setting('synth.polyphony', 128) # int -> setint fs.setting('audio.driver', 'alsa') # str -> setstr ``` -------------------------------- ### tuning_dump Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-player.md Retrieves microtuning offsets for a given bank and program. ```APIDOC ## `tuning_dump` ### Description Gets tuning (microtuning) information for a given bank and preset. Fills a `(c_double * 128)()` array via `fluid_synth_tuning_dump`, passing `None`/`0` for the name buffer and length. ### Method `tuning_dump` ### Signature ```python def tuning_dump(self, bank, prog): ``` ### Parameters - **bank** (int) - Required - Tuning bank. - **prog** (int) - Required - Tuning program. ### Returns a sequence of 128 floats — the tuning offset for each MIDI note, measured in cents (0.0 = standard tuning). ### Example ```python tuning = fs.tuning_dump(0, 0) print(tuning[60]) # cents offset of middle C ``` ``` -------------------------------- ### system_reset() Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/synth-midi.md Stops all notes and resets all programs on the synthesizer. This method performs a full system reset, returning the synthesizer to its default state. ```APIDOC ## system_reset() ### Description Stops all notes and resets all programs. ### Method system_reset ### Signature ```python def system_reset(self): ``` ### Parameters None. ### Returns The `fluid_synth_system_reset` status int. ``` -------------------------------- ### Modulator.__init__ constructor Source: https://github.com/amberwhitehead/pyfluidsynth/blob/master/_autodocs/api-reference/modulator.md Constructor for the Modulator class. Creates a new fluid_mod_t handle and stores it in self.mod. Takes no parameters and returns a new Modulator instance. ```python def __init__(self): ```