Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Last active April 11, 2024 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpotlightKid/e7f787cc142c45399f71296ac8a3de57 to your computer and use it in GitHub Desktop.
Save SpotlightKid/e7f787cc142c45399f71296ac8a3de57 to your computer and use it in GitHub Desktop.
Change program number of MIDI Program Change events according to given mapping
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Example script which maps program change numbers."""
from miditk.smf import MidiFileReader, MidiFileWriter
class ProgramChangeMapper(MidiFileWriter):
"""Change program number of Program Change events according to given mapping."""
def __init__(self, outfile, pcmap, channel=None, track=None):
self.pcmap = pcmap
self.channel = (channel,) if isinstance(channel, int) else channel
self.track = (track,) if isinstance(track, int) else track
super().__init__(outfile)
def program_change(self, channel, program):
if ((self.channel is None or channel in self.channel) and
(self.track is None or self.current_track in self.track)):
program = self.pcmap.get(program, program)
super().program_change(self, channel, min(127, max(0, program)))
if __name__ == '__main__':
import sys
infilename = sys.argv.pop(1)
outfilename = sys.argv.pop(1)
# Program change mapping
pcmap = {
0: 40, # Ac. Piano -> Strings
32: 33, # Ac. Bass -> Electric Bass
}
# Create parser and event handler
with open(outfilename, 'wb') as smf:
midiout = ProgramChangeMapper(smf, pcmap)
midiin = MidiFileReader(infilename, handler=midiout)
# Now do the processing.
midiin.read()
@SpotlightKid
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment