def __init__(self): self.fs = fluidsynth.Synth() self.fs.start() sfid = self.fs.sfload("FORE.sf2") self.fs.program_select(0, sfid, 0, 0)
from datetime import datetime import fluidsynth import fractions import math import numpy as np import pychord import simpleaudio as sa import threading from time import sleep import util.util as util import util.constants as constants fs = [fluidsynth.Synth() for i in range(2)] for f in fs: f.start() sfid = f.sfload("resources/soundfont.sf2") f.program_select(0, sfid, 0, 0) def play_chord(chord, root_pitch, duration): global async_playing, async_notes if async_playing: for note in async_notes: fs[0].noteoff(0, note) async_playing = False components = chord.components_with_pitch(root_pitch) notes = util.sequence_to_midi(components) for note in notes: fs[0].noteon(0, note, 80) sleep(duration) for note in notes:
print('==================================================') sys.stdout.flush() try: ser = serial.Serial( port=rng_com_port, timeout=10) # timeout set at 10 seconds in case the read fails except: print('Port Not Usable!') print('Do you have permissions set to read ' + rng_com_port + ' ?') if (ser.isOpen() == False): ser.open() ser.setDTR(True) ser.flushInput() sys.stdout.flush() fs = fluidsynth.Synth() fs.start(driver='dsound') # use DirectSound driver sfid = fs.sfload( r'C:\Users\Aslan\Documents\HALO Development\FluidTest\FluidR3_GM\FluidR3_GM.sf2' ) # replace path as needed fs1 = fluidsynth.Synth() fs1.start(driver='dsound') # use DirectSound driver sfid1 = fs1.sfload( r'C:\Users\Aslan\Documents\HALO Development\FluidTest\FluidR3_GM\FluidR3_GM.sf2' ) # replace path as needed fs1.program_select(0, sfid, 0, PentSound) fs.program_select(0, sfid, 0, ChordSound) Pll = (RNG_BytesPerInterval * 4) - PentThres
import time import numpy import pyaudio import fluidsynth from fluidsynth import * 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)) print("111") print(s) print("222") # settings = new_fluid_settings() # synth = new_fluid_synth(settings) # sfid = fl.sfload("/Users/yuhaomao/Desktop/pyfluidsynth/test/example.sf2", 7) sfid = fl.sfload("/Users/yuhaomao/Downloads/Steinway B-JNv2.0.sf2") fl.program_select(0, sfid, 0, 0) # (channel, soundfont ID, bank, preset ) fl.noteon(0, 60, 100) # fl.noteon(0, 67, 30) # fl.noteon(0, 76, 30) # fluidsynth.fluid_synth_noteon("",0, 60, 100) # Chord is held for 2 seconds
def __init__(self): self.fs = fluidsynth.Synth() self.channels = {}
def __init__(self): super().__init__() self.synth = fluidsynth.Synth() self.synth.start(driver="alsa") sfid = self.synth.sfload("example.sf2") self.synth.program_select(0, sfid, 0, 0)
except (ImportError, AttributeError): # if we're here, it's probably because fluidsynth wasn't installed logging.debug("Loading of pyfluidsynth failed again.") fluidsynth = None logging.warning( "Fluidsynth could not be loaded; synth output will not be available." ) if fluidsynth is not None and playback_settings.default_audio_driver == "auto": print("Testing for working audio driver...") found_driver = False for driver in [ 'alsa', 'coreaudio', 'dsound', 'Direct Sound', 'oss', 'pulseaudio', 'jack', 'portaudio', 'sndmgr' ]: test_synth = fluidsynth.Synth() test_synth.start(driver=driver) if test_synth.audio_driver is not None: playback_settings.default_audio_driver = driver playback_settings.make_persistent() found_driver = True test_synth.delete() print( "Found audio driver '{}'. This has been made the default, but it can be altered via " "the playback settings.".format(driver)) break test_synth.delete() if not found_driver: logging.warning( "No working audio driver was found; synth output will not be available." )
def miditowav(inst, mid, sf): #mid = pretty_midi.PrettyMIDI('./Music/kkhouse.mid') #1 pa = pyaudio.PyAudio() sd.query_devices() strm = pa.open(format=pyaudio.paInt16, channels=2, rate=44100, output=True) s = [] #result_array = mid2arry(mid) #selecting soundfont fl = fluidsynth.Synth() # Initial silence is 1 second #s = numpy.append(s, fl.get_samples(44100 * 1)) #fl.start('dsound') sfid = fl.sfload(r'C:\Users\User\Desktop\FluidR3_GM\yk.sf2') sfid = fl.sfload(sf) #selecting instrumnet fl.program_select(0, sfid, 0, 0) startdict = snotetodict(mid, inst) enddict = enotetodict(mid, inst) #notedict=startdict.copy() #notedict.update(enddict) notedict = nnotetodict(mid, inst) instrument = mid.instruments[inst] startarr = [] endarr = [] for note in instrument.notes: startarr.append(note.start) endarr.append(note.end) startkey = startdict.keys() startkey.sort() endkey = enddict.keys() endkey.sort() #delete same notes in notekey notekey = startkey + endkey notekey = set(notekey) notekey = list(notekey) notekey.sort() #print notekey print len(startarr), len(endarr) fl.noteon(0, 0, 0) fl.noteon(0, 30, 98) s = numpy.append(s, fl.get_samples(int(44100 * 1 / 2))) s = numpy.append(s, fl.get_samples(int(44100 * notekey[0] / 2))) playtime = {} #print notedict print mid.instruments[inst] for note in instrument.notes: fl.noteon(0, note.pitch, 98) s = numpy.append(s, fl.get_samples(int(44100 * 1 / 2))) #fl.noteoff(0,0) fl.delete() samps = fluidsynth.raw_audio_string(s) print(len(s)) print('Starting playback') #strm.write(samps) scaled = numpy.int16(s / numpy.max(numpy.abs(s)) * 32767) name = './Out/inst' + str(inst) + '.wav' write(name, 44100, scaled)
ser = serial.Serial(port=rng_com_port,timeout=10) # timeout set at 10 seconds in case the read fails # Open the serial port if it isn't open if(ser.isOpen() == False): ser.open() # Set Data Terminal Ready to start flow ser.setDTR(True) # This clears the receive buffer so we aren't using buffered data ser.flushInput() fs = fluidsynth.Synth() fs.start(driver = 'dsound') # use DirectSound driver sfid0 = fs.sfload(r'C:\Users\Aslan\Documents\TropicalHouseRNG\soundfonts\Timbres Of Heaven (XGM) 3.94.sf2') # replace path as needed fs1 = fluidsynth.Synth() fs1.start(driver = 'dsound') # use DirectSound driver sfid1 = fs1.sfload(r'C:\Users\Aslan\Documents\TropicalHouseRNG\soundfonts\Timbres Of Heaven (XGM) 3.94.sf2') # replace path as needed fs2 = fluidsynth.Synth() fs2.start(driver = 'dsound') # use DirectSound driver sfid2 = fs2.sfload(r'C:\Users\Aslan\Documents\TropicalHouseRNG\soundfonts\Timbres Of Heaven (XGM) 3.94.sf2') # replace path as needed fs3 = fluidsynth.Synth() fs3.start(driver = 'dsound') # use DirectSound driver sfid3 = fs3.sfload(r'C:\Users\Aslan\Documents\TropicalHouseRNG\soundfonts\Timbres Of Heaven (XGM) 3.94.sf2') # replace path as needed
def __init__(self, sf2_File, **kwargs): super(Piano, self).__init__(**kwargs) self.size = (300, 300) self.Dim = 0.09090 self.ButtonHeight = 0.3 # new edition 11-29-15 # Frequency freq = 58 exitconst = 1 - self.Dim ExitButton = Button(text="exit", size_hint=(self.Dim - 0.0009, self.Dim - 0.0009), pos_hint={ "x": exitconst, "y": exitconst }) ExitButton.bind(on_press=self.superExit) self.add_widget(ExitButton) # White Piano keys btn0 = CustomButton(0, freq + 2, 110, text="", size_hint=(self.Dim - 0.0009, 2 * self.ButtonHeight), pos_hint={ "x": 0.0, "y": 0.0 }) btn1 = CustomButton(0, freq + 4, 110, text="", size_hint=(self.Dim - 0.0015, 2 * self.ButtonHeight), pos_hint={ "x": self.Dim, "y": 0.0 }) #0.2 btn2 = CustomButton(0, freq + 6, 110, text="", size_hint=(self.Dim - 0.0009, 2 * self.ButtonHeight), pos_hint={ "x": (2 * self.Dim - .001), "y": 0.0 }) #0.4 btn3 = CustomButton(0, freq + 7, 110, text="", size_hint=(self.Dim - 0.0009, 2 * self.ButtonHeight), pos_hint={ "x": (3 * self.Dim), "y": 0.0 }) #0.2 btn4 = CustomButton(0, freq + 9, 110, text="", size_hint=(self.Dim - 0.0009, 2 * self.ButtonHeight), pos_hint={ "x": (4 * self.Dim), "y": 0.0 }) btn5 = CustomButton(0, freq + 11, 110, text="", size_hint=(self.Dim - 0.0015, 2 * self.ButtonHeight), pos_hint={ "x": (5 * self.Dim), "y": 0.0 }) btn6 = CustomButton(0, freq + 13, 110, text="", size_hint=(self.Dim - 0.0009, 2 * self.ButtonHeight), pos_hint={ "x": (6 * self.Dim), "y": 0.0 }) btn7 = CustomButton(0, freq + 14, 110, text="", size_hint=(self.Dim - 0.0009, 2 * self.ButtonHeight), pos_hint={ "x": (7 * self.Dim), "y": 0.0 }) btn8 = CustomButton(0, freq + 16, 110, text="", size_hint=(self.Dim - 0.0015, 2 * self.ButtonHeight), pos_hint={ "x": (8 * self.Dim), "y": 0.0 }) btn9 = CustomButton(0, freq + 18, 110, text="", size_hint=(self.Dim - 0.0009, 2 * self.ButtonHeight), pos_hint={ "x": (9 * self.Dim - .001), "y": 0.0 }) btn10 = CustomButton(0, freq + 19, 110, text="", size_hint=(self.Dim - 0.0009, 2 * self.ButtonHeight), pos_hint={ "x": (10 * self.Dim), "y": 0.0 }) btn1.bind(on_press=self.btn_pressed) btn1.bind(on_release=self.btn_released) # White Piano key bindings btn0.bind(on_press=self.btn_pressed) btn0.bind(on_release=self.btn_released) btn1.bind(on_press=self.btn_pressed) btn1.bind(on_release=self.btn_released) btn2.bind(on_press=self.btn_pressed) btn2.bind(on_release=self.btn_released) btn3.bind(on_press=self.btn_pressed) btn3.bind(on_release=self.btn_released) btn4.bind(on_press=self.btn_pressed) btn4.bind(on_release=self.btn_released) btn5.bind(on_press=self.btn_pressed) btn5.bind(on_release=self.btn_released) btn6.bind(on_press=self.btn_pressed) btn6.bind(on_release=self.btn_released) btn7.bind(on_press=self.btn_pressed) btn7.bind(on_release=self.btn_released) btn8.bind(on_press=self.btn_pressed) btn8.bind(on_release=self.btn_released) btn9.bind(on_press=self.btn_pressed) btn9.bind(on_release=self.btn_released) btn10.bind(on_press=self.btn_pressed) btn10.bind(on_release=self.btn_released) # White Piano keys added self.add_widget(btn0) self.add_widget(btn1) self.add_widget(btn2) self.add_widget(btn3) self.add_widget(btn4) self.add_widget(btn5) self.add_widget(btn6) self.add_widget(btn7) self.add_widget(btn8) self.add_widget(btn9) self.add_widget(btn10) # Black Piano keys Bbtn0 = CustomButton(0, freq + 3, 110, text="", size_hint=(0.8 * self.Dim, self.ButtonHeight), pos_hint={ "x": (0.5 * self.Dim), "y": .3 }) Bbtn1 = CustomButton(0, freq + 5, 110, text="", size_hint=(0.8 * self.Dim, self.ButtonHeight), pos_hint={ "x": (1.5 * self.Dim), "y": .3 }) Bbtn2 = CustomButton(0, freq + 8, 110, text="", size_hint=(0.8 * self.Dim, self.ButtonHeight), pos_hint={ "x": (3.5 * self.Dim), "y": .3 }) Bbtn3 = CustomButton(0, freq + 10, 110, text="", size_hint=(0.8 * self.Dim, self.ButtonHeight), pos_hint={ "x": (4.5 * self.Dim), "y": .3 }) Bbtn4 = CustomButton(0, freq + 12, 110, text="", size_hint=(0.8 * self.Dim, self.ButtonHeight), pos_hint={ "x": (5.5 * self.Dim), "y": .3 }) Bbtn5 = CustomButton(0, freq + 15, 110, text="", size_hint=(0.8 * self.Dim, self.ButtonHeight), pos_hint={ "x": (7.5 * self.Dim), "y": .3 }) Bbtn6 = CustomButton(0, freq + 17, 110, text="", size_hint=(0.8 * self.Dim, self.ButtonHeight), pos_hint={ "x": (8.5 * self.Dim), "y": .3 }) # Black Piano key bindings Bbtn0.bind(on_press=self.btn_pressed) Bbtn0.bind(on_release=self.btn_released) Bbtn1.bind(on_press=self.btn_pressed) Bbtn1.bind(on_release=self.btn_released) Bbtn2.bind(on_press=self.btn_pressed) Bbtn2.bind(on_release=self.btn_released) Bbtn3.bind(on_press=self.btn_pressed) Bbtn3.bind(on_release=self.btn_released) Bbtn4.bind(on_press=self.btn_pressed) Bbtn4.bind(on_release=self.btn_released) Bbtn5.bind(on_press=self.btn_pressed) Bbtn5.bind(on_release=self.btn_released) Bbtn6.bind(on_press=self.btn_pressed) Bbtn6.bind(on_release=self.btn_released) Bbtn0.background_color = [0, 0, 0, 1] Bbtn1.background_color = [0, 0, 0, 1] Bbtn2.background_color = [0, 0, 0, 1] Bbtn3.background_color = [0, 0, 0, 1] Bbtn4.background_color = [0, 0, 0, 1] Bbtn5.background_color = [0, 0, 0, 1] Bbtn6.background_color = [0, 0, 0, 1] # Adding Black piano keys self.add_widget(Bbtn0) self.add_widget(Bbtn1) self.add_widget(Bbtn2) self.add_widget(Bbtn3) self.add_widget(Bbtn4) self.add_widget(Bbtn5) self.add_widget(Bbtn6) self.fs = fluidsynth.Synth() self.fs.start('alsa') # starting fluidsynth #sfid = self.fs.sfload("fs.sf2") # loading soundfont sfid = self.fs.sfload(sf2_File) self.fs.program_select(0, sfid, 0, 0)
def __init__(self): self.synth = fluidsynth.Synth() self.sf = self.synth.sfload("PokemonCrystal.sf2")
def enable(self): self.fs = fluidsynth.Synth() self.enabled = True
def __init__(self): super().__init__() self.setupUi(self) self.fs = fluidsynth.Synth(gain=1.2) self.fs.start('coreaudio') self.keys = [ self.C_3, self.Db3, self.D_3, self.Eb3, self.E_3, self.F_3, self.Gb3, self.G_3, self.Ab3, self.A_3, self.Bb3, self.B_3 ] self.choose_soundbank.pressed.connect(self.style_pressed_btn) self.choose_soundbank.released.connect(self.choose_files) self.record_btn.pressed.connect(self.style_pressed_btn) self.record_btn.released.connect(self.start_rec) self.record_btn.rec = False self.rec = [] self.rec_time = 0 self.play_btn.released.connect(self.play_rec) self.play_btn.pressed.connect(self.style_pressed_btn) self.playback = False self.set_btn_released_style(self.play_btn) self.set_btn_released_style(self.choose_soundbank) self.set_btn_released_style(self.record_btn) self.set_btn_released_style(self.prev_oct) self.set_btn_released_style(self.next_oct) self.oct_now = self.oct.value() + 1 self.oct.valueChanged.connect(self.set_octave) self.oct.setValue(3) self.oct.lineEdit().setReadOnly(True) self.prev_oct.released.connect(self.prev_octave) self.next_oct.released.connect(self.next_octave) self.prev_oct.pressed.connect(self.style_pressed_btn) self.next_oct.pressed.connect(self.style_pressed_btn) self.gr_piano.path = './SoundFonts/Piano Grand.SF2' self.piano_col.path = './SoundFonts/Piano Collection.SF2' self.ac_guitar.path = './SoundFonts/AcousticGuitar.SF2' self.user_sb.path = None self.user_sb.setEnabled(False) for rb in self.buttonGroup.buttons(): rb.released.connect(self.set_soundbank) self.buttonGroup.buttons()[0].setChecked(True) self.buttonGroup.buttons()[0].released.emit() self.C_3.setText('Z') self.Db3.setText('S') self.D_3.setText('X') self.Eb3.setText('D') self.E_3.setText('C') self.F_3.setText('V') self.Gb3.setText('G') self.G_3.setText('B') self.Ab3.setText('H') self.A_3.setText('N') self.Bb3.setText('J') self.B_3.setText('M') for key in self.keys: key.setStyleSheet( 'background-color: white; border-color: black; border-style: solid; border-width: 4px; ' 'padding-bottom: -150px; font-size: 25px') key.pressed.connect(self.key_pressed) key.released.connect(self.key_released) key.setAutoRepeat(True) key.setAutoRepeatDelay(10**10) key.setAutoRepeatInterval(10**10) key._state = 0 key.proc = None key.sharp = False i = 1 while i < len(self.keys): self.keys[i].setStyleSheet( 'background-color: #545556; border-color: black; border-style: solid;' 'border-width: 4px; padding-bottom: -75px; font-size: 25px; color: white' ) self.keys[i].sharp = True if i == 3: i += 1 i += 2
def setup_audio(): fl = fluidsynth.Synth(samplerate=constants.AUDIO_SAMPLE_RATE) sfid = fl.sfload(SOUND_FONT_FILEPATH) fl.program_select(0, sfid, 0, 0) return fl
def miditowav(self, inst, mid, sf, inst_index=0): #mid = pretty_midi.PrettyMIDI('./Music/kkhouse.mid') #1 pa = pyaudio.PyAudio() sd.query_devices() strm = pa.open(format=pyaudio.paInt16, channels=2, rate=44100, output=True) s = [] #selecting soundfont fl = fluidsynth.Synth() # Initial silence is 1 second #s = numpy.append(s, fl.get_samples(44100 * 1)) #fl.start('dsound') #sfid = fl.sfload(r'C:\Users\User\Desktop\FluidR3_GM\yk.sf2') #sfid = fl.sfload(sf) #selecting instrumnet fl.program_select(0, sfid, 0, inst_index) startdict = snotetodict(mid, inst) enddict = enotetodict(mid, inst) #notedict=startdict.copy() #notedict.update(enddict) notedict = nnotetodict(mid, inst) instrument = mid.instruments[inst] print instrument.is_drum ''' if instrument.is_drum==True: sfid=fl.sfload('C:\Users\User\Desktop\FluidR3_GM\FluidR3_GM.sf2') fl.program_select(10, sfid, 0, 35) ''' startarr = [] endarr = [] for note in instrument.notes: startarr.append(note.start) endarr.append(note.end) startkey = startdict.keys() startkey.sort() endkey = enddict.keys() endkey.sort() #delete same notes in notekey notekey = startkey + endkey notekey = set(notekey) notekey = list(notekey) notekey.sort() print inst, len(startarr), len(endarr) fl.noteon(0, 0, 0) s = numpy.append(s, fl.get_samples(int(44100 * notekey[0] / 2))) playtime = {} notekey.append(notekey[len(notekey) - 1] + 1) for i in range(len(notekey) - 1): term = 0 pl = 0 ''' for note in notedict[notekey[i]]: if notekey[i] == note.start: fl.noteon(0, note.pitch, note.velocity) playtime=note.end-note.start print notekey[i],note.pitch,'start' elif notekey[i] == note.end: s = numpy.append(s, fl.get_samples(int(44100 * playtime / 2))) fl.noteoff(0, note.pitch) print notekey[i],note.pitch, 'end' ''' #print notekey[i],notedict[notekey[i]] for j in range(len(notedict[notekey[i]])): note = notedict[notekey[i]][j] #print "i:",i,"inst:",inst,note if notekey[i] == note.start: #beacuse fluidsynth can't make note which have pitch more than 88(when sf is koto) if note.pitch > 120: fl.noteon(0, note.pitch - 12, note.velocity) # beacuse fluidsynth can't make note which have pitch lee than 48(when sf is koto) #elif note.pitch<48: #fl.noteon(0,note.pitch+12,note.velocity) else: fl.noteon(0, note.pitch, note.velocity) elif notekey[i] == note.end: fl.noteoff(0, note.pitch) p = 0 term = notekey[i + 1] - notekey[i] s = numpy.append(s, fl.get_samples(int(44100 * term / 2))) fl.delete() samps = fluidsynth.raw_audio_string(s) print(len(s)) print('Starting playback') #strm.write(samps) #scaled = numpy.int16(s/numpy.max(numpy.abs(s)) * 32767) scaled = numpy.int16(s * 0.8 / numpy.max(numpy.abs(s)) * 32767) name = './Out/inst' + str(inst) + '.wav' write(name, 44100, scaled) #playsound(name) if self.maxendtime < notekey[len(notekey) - 1]: self.maxendtime = max(notekey[len(notekey) - 1], self.maxendtime) self.maxendindex = inst
notes = range(0, 127) velocities = [1, 31, 61, 91, 111, 127] fs = 44100 duration = 4 decay = 1 pack = sys.argv[1].split('.')[0] wav_parameters = (2, 2, fs, 0, 'NONE', 'not compressed') if os.path.exists(pack): shutil.rmtree(pack) os.makedirs(pack) config = open('%s/config.txt' % pack, 'w') synth = fluidsynth.Synth() sfid = synth.sfload(sys.argv[1]) synth.program_select(0, sfid, 0, 0) sys.stderr.write('\nUnpacking Soundfonts to .wav files.......') for note in notes: config.write('\n%d ' % note) sys.stderr.write('\n%d ' % note) for velocity in velocities: samples = [] synth.noteon(0, note, velocity) samples = numpy.append(samples, synth.get_samples(duration * fs))
mode = OperationMode(train=False,new_init=False,control=True) synth = ANNeSynth(mode) synth.load_weights_into_memory() # Finds all ports with MIDI attachments print(mido.get_input_names()) # Opens the port with the desired controller control = 'KeyLab 88' inport = mido.open_input(control) # initialize fluidsynth fs = fluidsynth.Synth(gain=0.20000000000000001) # NOTE: may need to change driver depending on machine fs.start(driver='coreaudio') # load default instrument sfid = fs.sfload("somesound.sf2") #if some crash happens and can't be loaded, change this to be test.sf2 fs.program_select(0, sfid, 0, 0) notearray = [] div_fac = 100 # 31.75
def __init_fluidsynth(self): self.__synth = fluidsynth.Synth() self.__synth.start() self.__soundfont_id = self.__synth.sfload(self.soundfont_filepath)
def fluidsynth(self, fs=44100, sf2_path=None): """Synthesize using fluidsynth. Parameters ---------- fs : int Sampling rate to synthesize. sf2_path : str Path to a .sf2 file. Default ``None``, which uses the TimGM6mb.sf2 file included with ``pretty_midi``. Returns ------- synthesized : np.ndarray Waveform of the MIDI data, synthesized at ``fs``. """ # If sf2_path is None, use the included TimGM6mb.sf2 path if sf2_path is None: sf2_path = pkg_resources.resource_filename(__name__, DEFAULT_SF2) if not _HAS_FLUIDSYNTH: raise ImportError("fluidsynth() was called but pyfluidsynth " "is not installed.") if not os.path.exists(sf2_path): raise ValueError("No soundfont file found at the supplied path " "{}".format(sf2_path)) # If the instrument has no notes, return an empty array if len(self.notes) == 0: return np.array([]) # Create fluidsynth instance fl = fluidsynth.Synth(samplerate=fs) # Load in the soundfont sfid = fl.sfload(sf2_path) # If this is a drum instrument, use channel 9 and bank 128 if self.is_drum: channel = 9 # Try to use the supplied program number res = fl.program_select(channel, sfid, 128, self.program) # If the result is -1, there's no preset with this program number if res == -1: # So use preset 0 fl.program_select(channel, sfid, 128, 0) # Otherwise just use channel 0 else: channel = 0 fl.program_select(channel, sfid, 0, self.program) # Collect all notes in one list event_list = [] for note in self.notes: event_list += [[note.start, 'note on', note.pitch, note.velocity]] event_list += [[note.end, 'note off', note.pitch]] for bend in self.pitch_bends: event_list += [[bend.time, 'pitch bend', bend.pitch]] for control_change in self.control_changes: event_list += [[ control_change.time, 'control change', control_change.number, control_change.value ]] # Sort the event list by time, and secondarily by whether the event # is a note off event_list.sort(key=lambda x: (x[0], x[1] != 'note off')) # Add some silence at the beginning according to the time of the first # event current_time = event_list[0][0] # Convert absolute seconds to relative samples next_event_times = [e[0] for e in event_list[1:]] for event, end in zip(event_list[:-1], next_event_times): event[0] = end - event[0] # Include 1 second of silence at the end event_list[-1][0] = 1. # Pre-allocate output array total_time = current_time + np.sum([e[0] for e in event_list]) synthesized = np.zeros(int(np.ceil(fs * total_time))) # Iterate over all events for event in event_list: # Process events based on type if event[1] == 'note on': fl.noteon(channel, event[2], event[3]) elif event[1] == 'note off': fl.noteoff(channel, event[2]) elif event[1] == 'pitch bend': fl.pitch_bend(channel, event[2]) elif event[1] == 'control change': fl.cc(channel, event[2], event[3]) # Add in these samples current_sample = int(fs * current_time) end = int(fs * (current_time + event[0])) samples = fl.get_samples(end - current_sample)[::2] synthesized[current_sample:end] += samples # Increment the current sample current_time += event[0] # Close fluidsynth fl.delete() return synthesized
def init(self): self.fsynth = fs.Synth()
def draw_rings(self): """ Draws the rings outward from the starting position and plays the notes in each ring.""" cells = self.world.cells screen = self.world.screen # Initialize the synthesizer and load sound fonts fs = fluidsynth.Synth() fs.start(driver="alsa") ids = [] for s in sound_list: ids.append(fs.sfload(s)) short = [] held = [] # Loops through each ring for ring in self.new_rings.values(): # Checks if stop button is pressed to stop playback for event in pygame.event.get(): if event.type is pygame.MOUSEBUTTONDOWN \ and self.world.is_touching(event.pos, self.world.buttons['P']): self.world.mode *= -1 # Breaks playback loop if stopped if self.world.mode > 0: break # Colors the cells in the current ring gray and adds the notes # represented by note blocks to lists to be played for coord in ring: cell = cells[coord] coords = self.world.add_coords(cell.coords, (2, 2)) rect_dim = (32, 32) image_rect = pygame.Rect(coords, rect_dim) pygame.draw.rect(screen, GRAY, image_rect, 0) if coord in self.world.blocks.keys(): d = self.world.blocks[coord].d pitch = self.pos_to_note(coord, d) shape = self.world.blocks[coord].shape instr = self.world.blocks[coord].instr if shape == 'circle': short.append((pitch, ids[instr])) else: held.append((pitch, ids[instr])) # Plays notes in the lists for the current ring for note in short: fs.program_select(0, note[1], 0, 0) fs.noteon(0, note[0], 60) for note in held: fs.program_select(0, note[1], 0, 0) fs.noteon(0, note[0], 60) # Allows the gray rings to be drawn pygame.display.update() time.sleep(.3) # Ends any notes in the 'short' list for note in short: fs.noteoff(0, note[0]) short = [] # Clears the gray rings by redrawing everything else self.world.redraw() # At the end, stops any held notes, sets the mode to paused, and stops the Synth for note in held: fs.noteoff(0, note[0]) held = [] self.world.mode = 1 fs.delete()
def init(self): self.fs = fs.Synth(gain=1)
import pysynth import pygame, pygame.sndarray import numpy import fluidsynth import time 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() # test = ( ('c', 4), ('e', 4) ) # pysynth.make_wav(test, fn = "test.wav") # pygame.init()
from lib.upload_handler import UploadHandler from lib.soundfont_handler import SoundfontHandler from lib.effects_handler import EffectsHandler def make_app(): settings = {"template_path": "templates"} return tornado.web.Application([(r'/$', DashboardHandler), (r'/upload', UploadHandler), (r'/soundfont', SoundfontHandler), (r'/effects', EffectsHandler)], **settings) if __name__ == "__main__": app = make_app() app.listen(8000) config.synth = fluidsynth.Synth(MidiAutoconnect=1, cores=3, SynthChorusActive=0, SynthReverbActive=0) config.synth.start(driver="alsa", midi_driver="alsa_seq") sfFiles = [f for f in glob.glob("./sf2/**/*.sf2", recursive=True)] for f in sfFiles: config.fonts.append(f[6:]) util.loadConfig() util.loadSoundfont(config.config['current_font'], save=False) tornado.ioloop.IOLoop.current().start()