Esempio n. 1
0
    def __init__(self, packetlistener):
        self._packetlistener = packetlistener
        self._packetanalyser = PacketAnalyser(self._packetlistener)

        fluidsynth.init("Bandpass.sf2", 'alsa')

        self._music_loop()
Esempio n. 2
0
def fib_song():
    fluidsynth.init('soundfonts/grand_piano.sf2')
    comp = Composition()
    comp.add_track(fib_seq())
    comp.add_track(fib_seq(offset=4))
    comp.add_track(fib_seq(offset=8))
    fluidsynth.play_Composition(comp)
Esempio n. 3
0
def main():
    if not os.path.isfile('./data/probs.json'):
        print ('Creating json file...')
        fname = "./data/interval-5gram.csv"
        counts = get_counts(fname, 4)
        probs = get_probs(counts)
        with open('./data/probs.json', 'w') as outfile:
            json.dump(probs, outfile)

    with open('./data/probs.json', 'r') as infile:
        probs_dict = json.load(infile, encoding='utf-8')

    start_int = C4
    melody = []
    fluidsynth.init("/usr/share/sounds/sf2/FluidR3_GM.sf2", "alsa")

    streamer = stream_notes(probs_dict)
    for i in range(100):
        next_int = start_int + int(next(streamer))
        next_note = Note()
        next_note.from_int(next_int)

        melody.append(next_note)
        start_int = next_int
        print(next_note)
        fluidsynth.play_Note(next_note)
        time.sleep(.2)
Esempio n. 4
0
    def play(self):
        fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2', 'alsa')
        fluidsynth.set_instrument(0, self.instrument)  # Use channel 0

        self.previous = int(SoundGen.kNoteNone)  # Previously played note

        self.shift = random.randint(-10, 5)  # Allow the key to be shifted

        beat_tracker = int(0)  # 4/4 time.
        while self.should_stop == False:
            v = random.randint(65, 75)
            if beat_tracker % 8 == 0:
                # First beat, strong
                v = random.randint(85, 95)
            elif (beat_tracker - 4) % 8 == 0:
                # Third beat, semi-strong
                v = random.randint(75, 85)
            elif beat_tracker % 2 == 1:
                # Off-beat, very soft
                v = random.randint(55, 65)

            # Random note length
            possible_lengths = [
                4
            ] + [2] * 10 + [1] * 4  # 4 is 2 beats, 2 is 1 beat, 1 is half-beat
            if beat_tracker % 2 == 1:  # avoid non-half-beat if currently in half-beat
                possible_lengths += [1] * 20  # Add weight to half-beat
            length = random.choice(possible_lengths)
            beat_tracker += length

            if self.previous != SoundGen.kNoteNone:
                fluidsynth.stop_Note(self.previous + self.shift, 0)
            self.previous = SoundGen.__next_note__(self.previous)
            fluidsynth.play_Note(self.previous + self.shift, 0, v)
            time.sleep(length * self.OneBeatLength)
    def __init__(self, packetlistener):
        self._packetlistener = packetlistener
        self._packetanalyser = PacketAnalyser(self._packetlistener)

        fluidsynth.init("Bandpass.sf2", 'alsa')

        self._music_loop()
Esempio n. 6
0
def main():
	fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2',"alsa")
	solution = [52,52,53,55,55,53,52,50,48,48,50,52,52,50,50]
	#testSol = [1,3,53,55,55,53,52,50,48,48,50,52,52,50,50]
	population = createInitialPopulation(250, len(solution))
	#t = Track()
	#for note in findMostFit(population,solution):
	#	t + note
	#fluidsynth.play_Track(t,1)
	generation = 1
	highestFitness = calcFitness(findMostFit(population, solution), solution)
	print("Generation: 1")
	print("Initial Highest Fitness: " + str(highestFitness))
	#print(calcFitness(testSol,solution))

	while highestFitness < 1:
		population = createNewPopulation(population, solution, .01)
		generation = generation + 1
		highestFitness = calcFitness(findMostFit(population, solution), solution)
		print("Generation: " + str(generation))
		print("Highest Fitness level: " + str(highestFitness))
		if generation % 10 == 0:
			print("hi")
			t = Track()
			for noteInt in findMostFit(population,solution):
				newNote = Note()
				newNote.from_int(noteInt)
				t + newNote
			fluidsynth.play_Track(t,1)
			#time.sleep(10)
	t = Track()
	for note in findMostFit(population,solution):
		t + note
	fluidsynth.play_Track(t,1)
def generate_composition(pattern, progression_type, nb_bars, key="C", rythm=60):
    fluidsynth.init("198_u20_Electric_Grand.SF2") # permet d'initialiser l'instrument
    newComposition = Composition()

    progression_list = on_progression_type_change(progression_type, nb_bars)
    left_hand = generate_pattern(progression_list, key, pattern, nb_bars)
    newComposition.add_track(left_hand)
    MidiFileOut.write_Composition("myComposition.mid", newComposition, rythm, False)
Esempio n. 8
0
 def __init__(self, starting_note='C-3'):
     fluidsynth.init(path_to_instrument, audio_driver)
     self.starting_note = Note(starting_note)
     self.relative_major_scale = np.array([0, 2, 4, 5, 7, 9, 11])
     self.scale = self.relative_major_scale + int(self.starting_note)
     self.note = Note(self.starting_note)
     self.bar = Bar()
     fluidsynth.play_Note(self.note)
Esempio n. 9
0
def fluidsynth_init():
    '''
    fluidsynth_init - initializes fluidsynth to the soundfont file and sets the
    instrument for each channel according to the list in constants.py
    '''
    fluidsynth.init(general_soundfont, "alsa")
    for i in instruments:
        fluidsynth.set_instrument(i[0], i[1], i[2])
Esempio n. 10
0
    def __init__(self, master):

        frame = Frame(master)
        frame.pack()
       
	fluidsynth.init("ChoriumRevA.SF2")

        roman_num = [0,2,4,5,7,9,11]

        self.progression = []
        self.buttons = {}
        
        self.prog_var = StringVar()
        self.display = Label( master, textvariable = self.prog_var).pack()
        
        self.uniprog_var = StringVar()
        self.unidisplay = Label( master, textvariable = self.uniprog_var).pack()

	self.sug_var = StringVar()
	self.sug_label = Label( master, textvariable = self.sug_var).pack()	

    #### Chord Buttons ####
         
	self.key_btn = Listbox(frame)
        self.key_btn.bind("<<ListboxSelect>>", self.display_progression)
	self.key_btn.pack(side=BOTTOM)
        for k in number.keys():
            self.key_btn.insert(END, k)

        for ch in roman_num:
            
            btn = Button(frame, text=roman[ch], command=partial( self.print_ch, ch ) )
            btn.pack(side=LEFT)
            
            self.buttons[ ch ] = btn 

    #### other buttons ####
            
        self.pop = Button(frame, text='Del', command=self.pop_ch)
        self.pop.pack(side=BOTTOM)

	self.play = Button(frame, text='Play', command=self.play_prog)
	self.play.pack(side=TOP)

	self.sugg = Button(frame, text='?', command=self.suggest)
	self.sugg.pack(side=BOTTOM)	

	self.save_btn = Button(frame, text='Save', command=self.save_midi)
	self.save_btn.pack(side=TOP)

    #### Checkbox buttons for intervals ####
        self.add7_var = BooleanVar()
        self.add7 = Checkbutton( master, text="+ 7", variable = self.add7_var )
        self.add7.pack()

        self.maj_var = BooleanVar()
        self.maj = Checkbutton( master, text="Major", variable = self.maj_var )
        self.maj.pack()
Esempio n. 11
0
def erreproduzitu_marrazkia(screen):
    fluidsynth.init(
        '/home/galtzagorri/Mahaigaina/Arachno SoundFont - Version 1.0.sf2',
        "alsa")
    for i in range(0, len(zerrenda)):
        print zerrenda[i].posy
        nota = (zerrenda[i].posy) % 127
        fluidsynth.play_Note(nota, 1, 100)
        time.sleep(0.5)
Esempio n. 12
0
    def Open(self):

        pygame.mixer.init()
        pygame.mixer.music.load("short_music.wav")
        pygame.mixer.music.play()
        self.last_detect_time = time.time()

        fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2', "alsa")
        fluidsynth.set_instrument(0, 6)
        fluidsynth.set_instrument(1, 4)
Esempio n. 13
0
def playTrack(arr):
	fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2',"alsa")
	SF2 = '/usr/share/sounds/sf2/FluidR3_GM.sf2'
	if not fluidsynth.init(SF2):
		print "Couldn't load soundfont", SF2
		sys.exit(1)
	t = Track()
	for note in arr:
		t + note
	fluidsynth.play_Track(t,1)
Esempio n. 14
0
def playNotes(notes, xscale=0.01):
    fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2', "alsa")
    currTime = 0
    for n in notes:
        waitTime = n.startx * xscale - currTime
        currTime = n.startx * xscale
        fluidsynth.play_Note(pow(n.energy, 0.2), 0, 100)
        print("Played %s, Waiting for %s " % (n, waitTime))
        time.sleep(waitTime)

    fluidsynth.stop_everything()
Esempio n. 15
0
def playNotes(notes, xscale = 0.01):
    fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2',"alsa")
    currTime = 0
    for n in notes:
        waitTime = n.startx * xscale - currTime
        currTime = n.startx * xscale
        fluidsynth.play_Note(pow(n.energy, 0.2), 0, 100)
        print("Played %s, Waiting for %s " % (n, waitTime))
        time.sleep(waitTime)

    fluidsynth.stop_everything()
Esempio n. 16
0
def play_pattern(pattern_index, key):
    pattern = patterns.PATTERNS[pattern_index]
    fluidsynth.init("198_u20_Electric_Grand.SF2") # permet d'initialiser l'instrument

    previews_note = None
    b = Bar(key, (4, 4))
    position_note = 0
    already_used=[]
    for pattern_note in pattern :
        if position_note not in already_used :
            is_chord = chord_length(pattern_note, pattern, position_note)
            if is_chord[2] :
                note_list = []
                # c est un accord
                for p_note in pattern[is_chord[0]:is_chord[1]+1] :
                    note_str = get_note_pattern(p_note, key)
                    note = Note(note_str, p_note[5])
                    if previews_note is not None:
                        if p_note[4]=='+':
                            if int(note) < previews_note :
                                note.octave_up()
                        elif p_note[4]=='-':
                            if int(note) > previews_note :
                                note.octave_down()      
                    previews_note = int(note)
                    note_list.append(note)
                    
                for n in range(is_chord[0], is_chord[1]+1):
                    already_used.append(n)
                
                b.place_notes(note_list, pattern_note[1])

                        
            else :    
                note_str = get_note_pattern(pattern_note, key)
                note = Note(note_str, pattern_note[5])
                
                if previews_note is not None:
                    if pattern_note[4]=='+':
                        if int(note) < previews_note :
                            note.octave_up()

                    elif pattern_note[4]=='-':
                        if int(note) > previews_note :
                            note.octave_down()
                            
                previews_note = int(note)
                b.place_notes(note, pattern_note[1])
                already_used.append(position_note)
        position_note+=1
            
    fluidsynth.play_Bar(b, 1, 60)                      
Esempio n. 17
0
    def __init__(self):
        self.store = db()
        fluidsynth.init(MIDI_FILE, 'alsa')

        self.builder = gtk.Builder()
        self.builder.add_from_file('res/gui.glade')

        self.window = self.builder.get_object('window')
        self.new_evolution_dialog = self.builder.get_object('new_evolution_dialog')
        self.new_neural_network_dialog = self.builder.get_object('new_neural_network_dialog')
        self.open_evolution_dialog = self.builder.get_object('open_evolution_dialog')
        

        self.nn_list = gtk.ListStore(str)
        self.nn_combo = self.builder.get_object('nn_combo')
        self.nn_combo.set_model(self.nn_list)
        cell = gtk.CellRendererText()
        self.nn_combo.pack_start(cell, True)
        self.nn_combo.add_attribute(cell,'text', 0)

        self.update_nn_list()

        self.evolution_list = gtk.ListStore(str)
        self.evolution_combo = self.builder.get_object('evolution_combo')
        self.evolution_combo.set_model(self.evolution_list)
        cell = gtk.CellRendererText()
        self.evolution_combo.pack_start(cell, True)
        self.evolution_combo.add_attribute(cell, 'text', 0)

        self.update_evolution_list()

        self.genome_list = gtk.ListStore(int, str)
        self.genome_view = self.builder.get_object('genome_view')
        self.genome_view.set_model(self.genome_list)
        cell = gtk.CellRendererText()
        column = gtk.TreeViewColumn('Genome', cell, text=1)
        self.genome_view.append_column(column)

        self.controls = {
            'initialize': self.builder.get_object('initialize_button'),
            'evaluate': self.builder.get_object('evaluate_button'),
            'select' : self.builder.get_object('apply_selection_button'),
            'play' : self.builder.get_object('play_button')
        }

        self.console = gtk.TextBuffer()
        self.builder.get_object('console').set_buffer(self.console)
        
        # hide dialogs instead of destroying them for reuse
        self.hide_dialog = gtk.Widget.hide_on_delete

        self.builder.connect_signals(self)
Esempio n. 18
0
    def __init__(self, instrument=None):
        super(FlowTrack, self).__init__(instrument)

        if type(instrument) is Guitar:
            fluidsynth.init('soundfonts/acoustic_guitar.sf2')
        else:
            fluidsynth.init('soundfonts/grand_piano.sf2')

        self.rate = 100

        self.chords = []
        self.key = 'C'
        self.octave = 4
Esempio n. 19
0
    def __init__(self, instrument=None):
        super(FlowTrack, self).__init__(instrument)

        if type(instrument) is Guitar:
            fluidsynth.init('soundfonts/acoustic_guitar.sf2')
        else:
            fluidsynth.init('soundfonts/grand_piano.sf2')

        self.rate = 100

        self.chords = []
        self.key = 'C'
        self.octave = 4
Esempio n. 20
0
def main():

    # Parse command-line user arguments and initializes settings
    fluidsynth.init(st.SOUNDFONT)  # start FluidSynth

    # Change instrument
    # fluidsynth.set_instrument(1, 14)

    # Select game
    settings = SettingsContainer(game_menu())

    # Play Game
    while 1:
        new_question_rn(settings)
Esempio n. 21
0
    def setUp(self):
        soundfont = os.getenv("SOUNDFONT")
        if soundfont is None:
            raise ValueError(
                "A soundfont (*.sf2) file path must be provided in the SOUNDFONT environment variable"
            )

        self.tempdir = tempfile.mkdtemp()
        output_file = os.path.join(self.tempdir, "test.wav")

        fluidsynth.init(soundfont, file=output_file)
        fluidsynth.set_instrument(0, 0)
        s = SequencerObserver()
        fluidsynth.midi.attach(s)
Esempio n. 22
0
def main():
    comp = Composition()
    with open('out.txt', 'r') as f:
        lines = f.readlines()
        for line in lines:
            tb = TrackBuilder()
            symbols = line.rstrip().split(' ')[1:]
            print(symbols)
            for symbol in symbols:
                tb.add_symbol(symbol)
            track = tb.flush()
            comp.add_track(track)
    fluidsynth.init('../sfs/soundfont.sf2', 'alsa')
    fluidsynth.play_Composition(comp)
Esempio n. 23
0
def play_midi(midi_path, save_path, beats, midi_vel, stop_all,midi_device_nr):
    from mingus.midi import fluidsynth
    from mingus.containers.note import Note
    curr_path = lib.os.path.dirname(lib.os.path.abspath(__file__))
    fluidsynth.init("/Users/js/Desktop/sounds/Nice-Keys-PlusSteinway-JNv2.0.sf2")

    f = open(save_path + '/play_midi.csv', 'w+')                # open file to save log values
    f.write('time,beats,midi_note,midi_vel\n')                  # write first line with corresponding titles
    mid = lib.mido.MidiFile(midi_path+'.mid')                          # save parsed MIDI file using mido library
    s_times = []  # np.zeros((times[0],2))                      # create an empty array to storenote events in the MIDI file
    #port = lib.mido.open_output(lib.mido.get_output_names()[midi_device_nr.value]) # open port to send MIDI messages
    all_time = 0                                                # aggregate time for all the messages
    msg_count = 0                                               # this is to count MIDI messages with note information
    all_messages = []                                           # create an ampty array to only store note information and their position in the score
    for msg in mid:                                             # for every message in the midi file
        all_time += msg.time                                    # the file stores midi time based on previous onset, we h
        if hasattr(msg, 'note'):                                # checks that the MIDI message is Note
            #all_time += msg.time                                #
            all_messages.append(msg)                            # adds note message from MIDI file to our playback thing
            s_times.append([msg_count, all_time])               # array to store note score time
            msg_count += 1                                      # count of how many note messages there are in total
    s_times = lib.np.array(s_times)                             # convert array to numpy.array
    yo = lib.copy.deepcopy(s_times)                             # deepcopy the array so the original doesn't get manipulated
    while True:
        if len(yo) != 0:                                        # keep running the loop until there are no more notes to play
            #print 'here'
            if yo[0, 1] < beats.value:                          # if the playhead is larger than the first note in the array play the first note and then delete
                msgMIDI = all_messages[int(yo[0, 0])]           # add note information and it's timing to the midi message to be sent
                if midi_vel.value > 127:
                    msgMIDI.velocity = 127
                else:
                    msgMIDI.velocity = midi_vel.value                    # add velocity to the MIDI message to be sent
                f.write(                                        # store values for later analysis
                    "%f, %f, %f, %f\n" % (lib.time.time(), beats.value, all_messages[int(yo[0, 0])].note, midi_vel.value))
                msgMIDI.channel = 0
                note = Note(all_messages[int(yo[0, 0])].note-12)
                print note
                note.velocity = msgMIDI.velocity
                if msgMIDI.type == 'note_on':
                    fluidsynth.play_Note(note)
                if msgMIDI.type == 'note_off':
                    fluidsynth.stop_Note(note)
                #port.send(msgMIDI)                              # send the message using predefined port (midi device)
                yo = lib.np.delete(yo, 0, 0)                    # once the note has been played delete the first message
                #print beats.value/2
        else:                                                   # if there are no more notes to play
            f.close                                             # stop storing the values in csv
            stop_all.value = True                                 # flag to indicate to the rest of the system that the file has finished.
            print 'MIDI Playback Finished'                      # print for use rto acknowledge
            break
Esempio n. 24
0
    def build(self):
        fluidsynth.init(os.path.join(ROOT_DIR, 'sounds', 'FluidR3_GM.sf2'))
        self.midi_in = MidiInputDispatcher()
        midi_device = self.config.get('MIDI', 'Input device')
        if midi_device:
            self.midi_in.open_port(midi_device)

        self.setting_panel = Settings()

        party = PlayerParty()
        sm = TonePoemGame(OrderedDict([
            ('area', AreaScreen(name='area')),
            ('encounter', EncounterScreen(name='encounter', party=party))
        ]), app=self)
        return sm
Esempio n. 25
0
def main():
    # Initialize
    import settings as st  # parses command-line user arguments and initializes settings
    fluidsynth.init(st.SOUNDFONT)  # start FluidSynth

    # Change instrument
    # fluidsynth.set_instrument(1, 14)

    # Initialize Game
    from game_modes import game_modes
    st.CURRENT_MODE = game_modes[st.INITIAL_MODE]
    st.CURRENT_MODE.intro()

    while 1:
        st.CURRENT_MODE.new_question()
Esempio n. 26
0
def main():
	#take first channel of file    
	Fs, data = wavfile.read(INPUT_FILE)
	y = data[:,0]

	#load piano soundfont
	SF2 = 'audio/FazioliGrandPiano.sf2'
	if not fluidsynth.init(SF2):
		print ("Couldn't load soundfont", SF2)
	
	#initialize variables for windowing
	sampSize = (Fs * WINDOW_LEN)/2
	prevStart = 0
	end = int(sampSize)
	totalSamp = int(len(y)/(sampSize*2) *2)

	#get the chords of the smoothed input
	for j in range(0,totalSamp):
		getFrequencies(smooth(y[prevStart:end]),Fs)
		prevStart += sampSize
		end += sampSize

	#play the chord back out again
	for idx,chord in enumerate(BAR):
		fluidsynth.play_NoteContainer(chord)
		time.sleep(PLAYBACK)
	time.sleep(PLAYBACK+0.3)
Esempio n. 27
0
    def __init__(self):
        # possible fluidsynth guys
        ##main_volume(channel, value)
        ##modulation(channel, value)
        ##pan(channel, value)

        if not fluidsynth.init(
                os.path.join(config.RESOURCEdirectory, config.SOUNDfont),
                config.FLUIDSYNTHdriver):
            sys.exit(" COULD NOT LOAD SOUNDFONT PianoMenu.sf2 ")
        # set instruments on each channel.
        fluidsynth.set_instrument(
            config.PIANOchannel,  ## channel to set instrument on
            config.SOUNDfontPIANO)  ## instrument.  determined by sound font

        self.keysmod12 = [
            "C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"
        ]
        self.keyson = [0] * 12  # denotes all keys on in an octave
        self.newnotesonlist = [
        ]  # list of new [note,velocity] that player has hit
        self.newnotesofflist = [
        ]  # list of new note that player has taken fingers off of
        #self.noteson = set()    # set of notes that the player currently has down
        # commented out since it was crashing things to remove notes sometimes...
        self.pitchwheel = 64  # current value of the pitch wheel
        self.modwheel = 0  # current value of the mod wheel
        self.transientnotes = []
        pygame.midi.init()
Esempio n. 28
0
    def __init__(self, filename):
        fluidsynth.init(filename)
        note_names = ("C-4", "C#4", "D-4", "D#4", "E-4", "F-4", "F#4", "G-4", "G#4", "A-4", "A#4", "B-4",
                      "C-5", "C#5", "D-5", "D#5", "E-5", "F-5", "F#5", "G-5", "G#5", "A-5", "A#5", "B-5")
        coords = (15, 35, 52, 71, 88, 125, 144, 160, 180, 197, 216, 234, 
                  270, 289, 307, 325, 343, 378, 398, 415, 434, 452, 470, 487)
        
        self.is_pressed = dict.fromkeys(note_names, [False] * len(note_names))
        self.note_coordinate = dict(zip(note_names, coords))
        self.note_names = note_names

        self.window_title = 'Keyboard'
        cv2.namedWindow(self.window_title)
        self.img = cv2.imread('./resources/keyboard.jpg', cv2.CV_LOAD_IMAGE_COLOR)
        cv2.imshow(self.window_title, self.img)
        self.turn_sound_on()
    def __init__(self):

        self._notes = []
        self._bar = None
        self._durs = []
        self._index = 0
        self._key = ""
        self._bpm = 120
        self._dynamics = {}

        self.paused = False

        self._bar = Bar()

        fs.init("sound.sf2", "oss")
        mixer.init()
Esempio n. 30
0
    def __init__(self, soundfont_name=None):

        if soundfont_name is None:
            fluidsynth.init('../soundfonts/soundfont.sf2', 'alsa')
        else:
            fluidsynth.init(soundfont_name, 'alsa')

        self.m_chain = MarkovChain(get_all_progressions())
        self.sim = self.m_chain.infinite_progression()

        down1 = (0.7, 0.05, 0.2)
        down2 = (0.2, 0.05, 0.7)
        off = (0.0, 0.4, 0.1)

        self.bassproba = [down1, off, down2, off, down1, off, down2, off]

        self.current = self.m_chain.START
Esempio n. 31
0
def erreproduzitu_marrazkia2(screen):
    fluidsynth.init(
        '/home/galtzagorri/Mahaigaina/Arachno SoundFont - Version 1.0.sf2',
        "alsa")
    #fluidsynth.init('/home/galtzagorri/Mahaigaina/grand-piano-YDP-20160804.sf2',"alsa")
    for i in range(0, len(zerrenda)):
        print zerrenda[i].posy
        print zerrendaBase[i].posy
        nota = (zerrenda[i].posy) % 127
        nota2 = (zerrendaBase[i].posy) % 126
        t = threading.Thread(target=fluidsynth.play_Note(nota, 1, 100))
        t2 = threading.Thread(target=fluidsynth.play_Note(nota2, 1, 100))
        #t.start()
        #t2.start()
        #fluidsynth.play_Note(nota,1,100)
        #fluidsynth.play_Note(nota2,2,100)
        time.sleep(0.5)
Esempio n. 32
0
    def __init__(self, soundfont_name=None):

        if soundfont_name is None:
            fluidsynth.init('../soundfonts/soundfont.sf2', 'alsa')
        else:
            fluidsynth.init(soundfont_name, 'alsa')

        self.m_chain = MarkovChain(get_all_progressions())
        self.sim = self.m_chain.infinite_progression()

        down1 = (0.7, 0.05, 0.2)
        down2 = (0.2, 0.05, 0.7)
        off = (0.0, 0.4, 0.1)

        self.bassproba = [down1, off, down2, off, down1, off, down2, off]

        self.current = self.m_chain.START
Esempio n. 33
0
    def __init__(self, filename):
        fluidsynth.init(filename)
        note_names = ("C-4", "C#4", "D-4", "D#4", "E-4", "F-4", "F#4", "G-4",
                      "G#4", "A-4", "A#4", "B-4", "C-5", "C#5", "D-5", "D#5",
                      "E-5", "F-5", "F#5", "G-5", "G#5", "A-5", "A#5", "B-5")
        coords = (15, 35, 52, 71, 88, 125, 144, 160, 180, 197, 216, 234, 270,
                  289, 307, 325, 343, 378, 398, 415, 434, 452, 470, 487)

        self.is_pressed = dict.fromkeys(note_names, [False] * len(note_names))
        self.note_coordinate = dict(zip(note_names, coords))
        self.note_names = note_names

        self.window_title = 'Keyboard'
        cv2.namedWindow(self.window_title)
        self.img = cv2.imread('./resources/keyboard.jpg', cv2.IMREAD_COLOR)
        cv2.imshow(self.window_title, self.img)
        self.turn_sound_on()
def loadSynth():
    SF2 = '~/Depot/fluid-soundfont/FluidR3_GM2-2.SF2'

    if not fluidsynth.init(SF2, 'coreaudio'):
        print('Could not load soundfont', SF2)
        print(
            'Install FluidSynth soundfont (FluidR3_GM2-2.SF2) into the directory ~/Depot/fluid-soundfont.'
        )
        sys.exit(1)
Esempio n. 35
0
def main():
    if not fluidsynth.init(SF2):
        print "Couldn't load soundfont", SF2
        sys.exit(1)

    notes = []
    for fn in sys.argv[1:]:
        print fn
        read_notes(fn, notes)

    play_notes(notes)
Esempio n. 36
0
    def __init__(self, 
                 soundfont_file,
                 soundfont_driver="alsa",
                 valve_mapping=default_valve_mapping,
                 freq_ranges=default_freq_ranges,
                 note_mapping=default_note_mapping):
        """
        Initialize Trumpet
        """
        self.valve_mapping = valve_mapping # Valve to key map
        self.freq_ranges = freq_ranges     # Freq range to harmonic series
        # Note mapping indexed as [freq range index][valve combo (index)]
        self.note_mapping = note_mapping  

        # Initialize Fluidsynth
        self.soundfont_file = soundfont_file
        self.soundfont_driver = soundfont_driver
        fluidsynth.init(soundfont_file, soundfont_driver)
        # Keep track of the current note state
        self.current_note = "" 
        self.prev_freq = 0
Esempio n. 37
0
def generate_composition(pattern_index, progression_type, nb_bars, mode='none', key="C", rythm=60):
    fluidsynth.init("198_u20_Electric_Grand.SF2") # permet d'initialiser l'instrument
    newComposition = Composition()
    progression_list = on_progression_type_change(progression_type, nb_bars)
    
     # truc pour la main droite
    if nb_bars == 1 :
        phrase_list = choose_phrases(key, mode, nb_bars)
        right_hand = use_phrase(phrase_list, progression_list, nb_bars, pattern_index, mode='none', key="C")
    else :
        chorus = generate_chorus(progression_list, pattern_index, mode, key)
        #chorus retourne : une phrase de debut, une phrase de fin, 3 bars fixes
        phrase_list = choose_first_phrases(nb_bars, key, mode, chorus[1], chorus[2], pattern_index)
        right_hand = generate_long_right_hand(phrase_list, progression_list, nb_bars, pattern_index, mode, key, chorus)
    
    newComposition.add_track(right_hand)
    
    left_hand = generate_pattern(progression_list, key, pattern_index, nb_bars)
    newComposition.add_track(left_hand)
    MidiFileOut.write_Composition("myCompo.mid", newComposition, rythm, False)
   
    return newComposition
Esempio n. 38
0
def playProgression():
    progression = ["I", "vi", "ii", "iii7", "I7", "viidom7", "iii7", "V7"]
    key = "C"

    chords = progressions.to_chords(progression, key)

    if not fluidsynth.init(SF2):
        print "Couldn't load soundfont", SF2
        sys.exit(1)

    while 1:
        i = 0
        for chord in chords:
            c = NoteContainer(chords[i])
            l = Note(c[0].name)
            p = c[1]
            l.octave_down()
            print ch.determine(chords[i])[0]

            # Play chord and lowered first note
            fluidsynth.play_NoteContainer(c)
            fluidsynth.play_Note(l)
            time.sleep(1.0)

            # Play highest note in chord
            fluidsynth.play_Note(c[-1])

            # 50% chance on a bass note
            if random() > 0.5:
                p = Note(c[1].name)
                p.octave_down()
                fluidsynth.play_Note(p)
            time.sleep(0.50)

            # 50% chance on a ninth
            if random() > 0.5:
                l = Note(intervals.second(c[0].name, key))
                l.octave_up()
                fluidsynth.play_Note(l)
            time.sleep(0.25)

            # 50% chance on the second highest note
            if random() > 0.5:
                fluidsynth.play_Note(c[-2])
            time.sleep(0.25)

            fluidsynth.stop_NoteContainer(c)
            fluidsynth.stop_Note(l)
            fluidsynth.stop_Note(p)
            i += 1
        print "-" * 20
Esempio n. 39
0
def synthComm():
    # print "I AM IN synthComm"
    timeStart = time.time()
    fluidsynth.init(config.sf2Path)

    note = Note()
    ser = serial.Serial(config.megaPath, config.megaBaud,timeout = 1)
    fluidsynth.stop_Note(note)
    while config.playing:
        info = ser.readline()
        print info
        if info is not '' and len(info) == 9:
            # print info
            # print timeStart
            fluidsynth.stop_Note(note)
            # print "---"
            # print len(info)
            # print "---"

            timeElp, x, y, vel = parseInput(timeStart, info)
            n = pos2Num(x,y)
            # print n
            # print names[n]
            note = Note(names[n],octave)
            note.velocity = vel
            fluidsynth.play_Note(note)

            print "-----"
            print "Time: {0} \nPosition: {1},{2}\n Velocity: {3}".format(timeElp, x, y, vel)
            print "-----"
        else:
            fluidsynth.stop_Note(note)

                # config.userHits = np.hstack((config.userHits, np.array([[time],[vel],[x],[y])))
    # when done, close out connection
    ser.close()
    # print " I HAVE CLOSED THE connection"
    return
Esempio n. 40
0
def start():
    piano_folder = "25-Piano-Soundfonts"
    piano_options = convert(os.listdir(piano_folder))
    pp.pprint(piano_options)
    selected_piano = None
    while selected_piano is None:
        piano_name = input("Enter Piano: ")
        selected_piano = piano_options.get(piano_name)

    SF2 = f"{piano_folder}/{selected_piano}"
    print("Left Hand")
    pp.pprint(qwerty_keys_to_standard.get('left'))
    print("Right Hand")
    pp.pprint(qwerty_keys_to_standard.get('right'))
    if not fluidsynth.init(SF2):
        print("Couldn't load soundfont", SF2)
        sys.exit(1)
Esempio n. 41
0
    def __init__( self ):
    # possible fluidsynth guys
##main_volume(channel, value)
##modulation(channel, value)
##pan(channel, value)

        if not fluidsynth.init( os.path.join( config.RESOURCEdirectory, config.SOUNDfont), 
            config.FLUIDSYNTHdriver ):
            sys.exit(" COULD NOT LOAD SOUNDFONT PianoMenu.sf2 ")
        # set instruments on each channel.  
        fluidsynth.set_instrument( config.PIANOchannel,    ## channel to set instrument on
                                   config.SOUNDfontPIANO ) ## instrument.  determined by sound font

        self.keysmod12 = [ "C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B" ]
        self.keyson = [ 0 ]*12  # denotes all keys on in an octave
        self.newnotesonlist = [ ]   # list of new [note,velocity] that player has hit
        self.newnotesofflist = [ ]  # list of new note that player has taken fingers off of
        #self.noteson = set()    # set of notes that the player currently has down 
        # commented out since it was crashing things to remove notes sometimes...
        self.pitchwheel = 64    # current value of the pitch wheel
        self.modwheel = 0       # current value of the mod wheel
        self.transientnotes = []
        pygame.midi.init()
Esempio n. 42
0
    def __init__(self):

        if not fluidsynth.init(
                os.path.join(config.RESOURCEdirectory, config.SOUNDfont),
                config.FLUIDSYNTHdriver):
            sys.exit(" Kan de Fluidsynth Sountfont PianoMenu.sf2 niet laden ")
        # Een instrument geven aan je channels.
        fluidsynth.set_instrument(
            config.PIANOchannel,  ## channel voor je instrument.
            config.SOUNDfontPIANO)  ## instrument gebaseerd op je soundfont.

        self.keysmod12 = [
            "C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"
        ]
        self.keyson = [0] * 12  # Representeert alle keys in een octaaf
        self.newnotesonlist = [
        ]  # lijst van de noten die de gebruiker heeft aangeslagen.
        self.newnotesofflist = []  # Lijst van noten die gebruiker loslaat.
        #self.noteson = set()    # noten die gebruiker gebruikt.
        self.pitchwheel = 64
        self.modwheel = 0
        self.transientnotes = []
        pygame.midi.init()
Esempio n. 43
0
import json
import numpy
import os
import sys
import time
from mingus.midi import fluidsynth
fluidsynth.init(
    '/Users/paulodenwaldt/Desktop/NLP/finalproject/data/FluidR3_GM.sf2')

from itertools import dropwhile, takewhile
'''
The audio playback of this program depends on the mingus and fluidsynth libraries.
Both can be installed with pip or homebrew. (pip/brew install mingus, pip/brew install fluidsynth).
You will also need the FluidR3_GM.sf2 file - this contains the waveforms necessary
for synthesis. You can find it here: https://member.keymusician.com/Member/FluidR3_GM/index.html
Once you have these installed, just change the path in line 7 to wherever you installed 
the sf2 file to. 
'''

# To run this, you will need numpy. An example call is this:
# py -3.7 .\melody_generator_epoch.py 1750-1799 -debug
# (or whichever era you want to look at instead of 1750-1799), and the
# flag -debug is optional which prints progress as the program runs.

# The program requires that you have the unique-grams generated for
# the time period in the folder unique_ngrams_epochs,
# generated by n-gram_epoch_scraper.py, as well as a folder epochs_hmm
# with the same time periods which were generated by
# n-gram_epoch_predicter.py from the unique_ngrams_epochs folder.

# Note: older time periods may give short melodies as a result of
Esempio n. 44
0
def init(soundfont_path='FluidR3_GM.sf2', driver='alsa'):
    fluidsynth.init(soundfont_path, driver)
#William Ambrozic 2018
from turtle import *
import Tkinter as tk
from tkColorChooser import askcolor
from mingus.midi import fluidsynth
fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2', "alsa")


def getDots(Link, view):
    scale = 6  #increses / decreases the size of the patterns to a factor of scale
    t.tracer(0)
    for x in range(numONodes.get()):
        if (rainbow.get() == 0): t.dot(5, nodeColor.get())
        Link[x] = t.position()
        t.forward(scale * 360.0 / numONodes.get()
                  )  #I want all of the shapes to be to same relative size
        t.left(
            360.0 / numONodes.get()
        )  #After simpliying (n-2) * 180 given that I need to find the complimentary angle
    return Link


def createPoly(view):
    colors = [
        "#660000", "#990000", "#CC0000", "#FF0000", "#CC3333", "#FF6666",
        "#FF9999", "#FFCCCC", "#663300", "#993300", "#CC3300", "#FF3300",
        "#FF6600", "#FF6633", "#FF9966", "#FFCC99", "#996633", "#CC9900",
        "#FFCC00", "#FFFF00", "#FFFF33", "#FFFF66", "#FFFF99", "#FFFFCC",
        "#003300", "#006600", "#009900", "#00CC00", "#00FF00", "#66FF66",
        "#CCFFCC", "#003333", "#336666", "#009999", "#00CCCC", "#66CCCC",
        "#66FFCC", "#99FFCC", "#003399", "#0033FF", "#0066FF", "#00CCFF",
Esempio n. 46
0
#!/usr/bin python 

import constants as consts

from libavg import avg, Point2D
from mingus.midi import fluidsynth
from mingus.containers.Note import Note

SF2 = "GeneralUser.sf2"
if not fluidsynth.init(SF2, "alsa"):
	print "Couldn't load soundfont", SF2

class Key(avg.RectNode):
	def __init__(self, size, pos, pitch, isWhite, parent=None, **kwargs):
		super(Key, self).__init__(**kwargs)
		if parent:
			parent.appendChild(self)
		self.size = size
		self.pos = pos
		self.pitch = pitch
		self.isWhite = isWhite
		self.fillopacity = 1
		self.setNote()
		
		if self.isWhite:
			self.fillcolor = "FFFFFF"
			self.color = "000000"
			self.onDown = self.onWhiteDown
			self.onUp = self.onWhiteUp
			self.onOut = self.onWhiteOut
		else:
Esempio n. 47
0
from kivy.animation import Animation
from kivy.core.window import Window
from kivy.graphics import Color, Line, Bezier
from kivy.uix.widget import Widget
from kivy.uix.spinner import Spinner
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from mingus.core import notes, chords
from mingus.containers import *
from random import random
from math import ceil

from mingus.midi import fluidsynth
fluidsynth.init('fluid.sf2') #set soundfont

#initialize default settings
#these are changed by buttons
#so they are declared here globally
fluidsynth.set_instrument(1, 0)
octaveSet = 2
keySet = 'C'
scaleSet = 'Major'
notesChange = True #keep track of changes, so we don't have to recompute unnecessarily
allScales = {}
currentNotes = []

class SlateWidget(Widget):
	notesp = {} #contain playing notes
		
Esempio n. 48
0
Uses mingus fluidsynth.
"""
import sys, pdb, time, os
sys.path.append("..")

from util.constants import *
from core.Note import numToPitch_absolute, pitchToNum_absolute
from core.solver import make_var
import mingus.containers

# Try to initialize playback
curfiledir = os.path.split(os.path.abspath(os.path.realpath(__file__)))[0]
PATH_SOUNDFONT = os.path.join(curfiledir, "./TimGM6mb.sf2")
try:
    from mingus.midi import fluidsynth
    canPlayback = fluidsynth.init(PATH_SOUNDFONT, "pulseaudio")
except ImportError:
    print "Warning: Could not import mingus. Playback is not supported."
    canPlayback = False
if not canPlayback:
    print "Warning: Playback is not supported!"
else:
    print "Playback supported!"

def playSolution(solution):
    """ Plays back a given solution.
    INPUT:
      dict solution:
        NOTE: GUI passes in a list of the form:
          [["<singer><time>", int pitchnum], ...]
        Command-line interface uses a different representation than
Esempio n. 49
0
from mingus.midi import fluidsynth

fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2')

fluidsynth.play_Note(64,0, 100)
Esempio n. 50
0
	def __init__(self,sf_file,bpm):
		synth.init(sf_file,"alsa") #initialize synth module from Mingus with soundfont file and alsa as default
		self.bpm = float(bpm)
		self.me_time = float(240/bpm)  #Set the time in seconds that each measure in 4/4 time takes
Esempio n. 51
0
        p[0].append([p[1][0][0],p[1][0][1]])

def p_note_pitch_duration(p):
    'note : pitch DASH duration'
    p[0] = [[p[1],p[3]]]

def p_pitch_terminals(p):
    'pitch : LETTER DASH NUMBER'
    p[0] = Note(''.join(p[1:4]))

def p_duration_terminals(p):
    'duration : NUMBER'
    p[0] = int(p[1])

def p_error(p):
    print("parser: syntax error")

yacc.yacc()

if __name__ == '__main__':
    fluidsynth.init('sounds/electricPiano.SF2','coreaudio')
    while 1:
        try:
            s = raw_input(">>> ")
            if s == 'q': break
            if s == '': continue
        except EOFError:
            break
        result = yacc.parse(s)
        fluidsynth.play_Track(result,1,bpm)
Esempio n. 52
0
''' tester for mingus fluidsynth '''

from mingus.midi import fluidsynth
from mingus.containers import Note
import sys
import time
import random

fluidsynth.init("../HS_Magic_Techno_Drums.SF2")
names = ['A', 'Bb', 'B', 'C', 'Db','D','Eb', 'E', 'F', 'Gb','G','Ab']
# while(True):
# 	n = Note(names[random.randrange(0,11,1)], random.randrange(1,4,1))
# 	n.velocity = random.randrange(40,100,1)
# 	# fluidsynth.set_instrument(1, random.randrange(1,5,1), bank =1)
# 	fluidsynth.play_Note(n)
# 	time.sleep(.1*random.randrange(1,15,1))
# 	# fluidsynth.stop_Note(n)
# 	time.sleep(.5*random.randrange(1,15,1))
# 	# fluidsynth.play_Note(n)

for i in xrange(0,12):
	# for j in xrange(1,4):
	# 	n = Note(names[i],j)
	# 	fluidsynth.play_Note(n)
	# 	time.sleep(2)
	n = Note(names[i], 4)
	n.velocity = 127
	fluidsynth.play_Note(n)
	time.sleep(1)
Esempio n. 53
0
def run(**config_params):
    load_config(**config_params)
    fluidsynth.init(config.SOUNDFONT_FILE)
    bottle.run(host=config.HOST, port=config.PORT)
Esempio n. 54
0
def init():
   if not fluidsynth.init(SF2):
      print "Couldn't load soundfont", SF2
      sys.exit(1)
Esempio n. 55
0
"""
"""

from mingus.core import progressions, intervals, chords
from mingus.core.scales import ionian, aeolian, locrian, whole_note, mixolydian
from mingus.containers import NoteContainer, Note, Bar, Track, Composition
from mingus.midi import fluidsynth
import time, sys
import random
import math

solo_sound_font = "soundfont.sf2"

if not fluidsynth.init(solo_sound_font):
	print "Couldn't load soundfont", solo_sound_font
	sys.exit(1)

choose_scale = {'M' : ionian,
				'm' : aeolian,
				'dim' : locrian,
				'+' : whole_note,
				'7' : mixolydian,
				'm7': aeolian,
				'M7': ionian}

def generate_scale(chord_name):
	i = 1
	while chord_name[i] == 'b' or chord_name[i] == '#':
		i += 1
	return choose_scale[chord_name[i:]](chord_name[:i])
Esempio n. 56
0
	def setUp(self):
		fluidsynth.init("/home/bspaans/workspace/fluidsynth/ChoriumRevA.SF2")
		fluidsynth.set_instrument(0,0)
                s = SequencerObserver()
                fluidsynth.midi.attach(s)
Esempio n. 57
0
# Control beginning of solos and chords

solo_start = 8
solo_end = 20
chord_start = 16
chord_end = 24

# Channels

chord_channel = 1
chord_channel2 = 7
chord_channel3 = 3
bass_channel = 4
solo_channel = 13
random_solo_channel = False
if not fluidsynth.init(SF2):
    print "Couldn't load soundfont", SF2
    sys.exit(1)
chords = progressions.to_chords(progression, key)
loop = 1
while loop < song_end:
    i = 0
    if random_solo_channel:
        solo_channel = choice(range(5, 8) + [11])
    for chord in chords:
        c = NoteContainer(chords[i])
        l = Note(c[0].name)
        n = Note('C')
        l.octave_down()
        l.octave_down()
        print ch.determine(chords[i])[0]
Esempio n. 58
0
	if block.swing == "Default":
		block.swing = bool(options.swing)

def load_fluidsynth(options):
	if not options.no_fluidsynth:
		try:
			from mingus.midi import fluidsynth
		except ImportError, msg:
			raise OptionError, msg
		except:
			raise OptionError, "Couldn't load the FluidSynth bindings in mingus. Are you sure FluidSyth has been installed?"
		if hasattr(options, 'driver'):
			driver = options.driver
		else:
			driver = None
		if not fluidsynth.init(options.SF2, driver):
			raise OptionError, "Couldn't load '%s'." % options.SF2

def get_sequencer_from_cli():

	options, args = get_options()
	list_arguments(options)
	return get_sequencer(options)

def get_sequencer(options):
	movement = get_movement(options)
	movement.blocks = []
	movement.instruments = []
	set_ensemble(options, movement)
	set_instrument(options, movement)
	blocks = get_blocks(options)