Exemplo n.º 1
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)
Exemplo n.º 2
0
 def __init__(self, music_key, major, tempo, tsfile):
     self.key = music_key
     self.tempo = tempo
     self.timeseries = pd.read_csv(tsfile, sep='\s*,\s*', engine='python')
     self.composition = Composition()
     self.composition.set_author('Guido', '*****@*****.**')
     self.composition.set_title('Epidemics')
def createMingusComposition(intermed, timesig, bIsTreble, bSharps):
    comp = Composition()
    comp.set_title('Trilled Results')
    comp.set_author('Author')
    if bIsTreble: ins = TrebleInstrument('')
    else: ins = BassInstrument('')

    track = Track(ins)
    track.name = 'Part 1'
    comp.add_track(track)

    assert len(timesig) == 2 and isinstance(timesig[0], int) and isinstance(
        timesig[1], int)
    firstbar = Bar(meter=timesig)
    track.add_bar(firstbar)

    mapDurs = {
        int(intermed.baseDivisions * 4): 1.0,  #whole note,
        int(intermed.baseDivisions * 2): 2.0,  #half note
        int(intermed.baseDivisions * 1): 4.0,  #qtr note, and so on
        int(intermed.baseDivisions * 0.5): 8.0,
        int(intermed.baseDivisions * 0.25): 16.0,
        int(intermed.baseDivisions * 0.125): 32.0,
        int(intermed.baseDivisions * 0.0625): 64.0,
    }

    for note in intermed.noteList:
        if note.pitch == 0 or note.pitch == (0, ):  # a rest
            thepitches = tuple()
        else:  # a note
            thepitches = []
            for pitch in note.pitch:
                pname, poctave = music_util.noteToName(pitch, bSharps)
                thepitches.append(pname + '-' + str(poctave))

        dur = note.end - note.start
        if dur not in mapDurs:
            raise NotesinterpretException('Unknown duration:' + str(dur))
        notecontainer = NoteContainer(thepitches)
        notecontainer.tied = note.isTied
        bFit = track.add_notes(notecontainer, mapDurs[dur])
        assert bFit

        #note that, naturally, will enforce having correct measure lines, since going across barline throughs exception

    return comp
Exemplo n.º 4
0
    def buildComposition(self, compose):
        """
        function to parse file into a composition
        :param compose: contents of midi file
        :return: tuple containing composition and length of composition
        """
        c = Composition()
        count = 0
        #get components
        for track in compose:
            t = self.track
            for bar in track:
                for info in bar:
                    #get note information and duration
                    t.add_notes(info[2], duration=info[1])
                    count = round(count + info[0], 2)
            c.add_track(t)

        return c, count
Exemplo n.º 5
0
def setup_tracks(midi_file_out=None):
    from tracks import melodies, cantus_firmus, key, meter, species, author
    # Create a composition, and add the vocal tracks to it.
    composition = Composition()
    composition.set_title('Counterpoint Exercise', '')
    composition.set_author(author, '')

    # Set up our vocal 'tracks' with the notes, key, meter defined in tracks.py
    tracks = {}
    for voice in [Soprano, Alto, Tenor, Bass]:
        if len(melodies[voice.name]):
            tracks[voice.name] = Track(instrument=voice())
            tracks[voice.name].add_bar(Bar(key=key, meter=meter))
            tracks[voice.name].name = voice.name
            for note in melodies[voice.name]:
                tracks[voice.name].add_notes(*note)
            composition.add_track(tracks[voice.name])

    if midi_file_out is not None:
        # Save the midi file!
        write_Composition(midi_file_out, composition, verbose=True)

    return composition, [], species
Exemplo n.º 6
0
    async def run(self):
        while await self.receive():  # flush messages
            pass

        c = Composition()
        c.set_author("amg")
        c.set_title(CFG.OUTPUT_PREFIX + self.agent.name)
        c.add_track(self.agent.get("melody_track"))
        c.add_track(self.agent.get("accompaniment_track"))
        # fluidsynth.init("4U-Yamaha C5 Grand-v1.5.sf2", "alsa")
        # fluidsynth.play_Composition(c)
        midi_file_out.write_Composition(
            CFG.OUTPUT_FOLDER + CFG.OUTPUT_PREFIX + self.agent.name + ".mid",
            c, CFG.SONG_TEMPO)
        l = lilypond.from_Composition(c)
        extra = "  \\score { \\new PianoStaff << \\set PianoStaff.instrumentName = #\"Piano  \" \\new Staff = \"upper\" \\upper \\new Staff = \"lower\" \\lower  >> \\layout { }  }"
        l2 = l.replace("{ {", "upper = {x {x", 1).replace(
            "{ {", "lower = { {", 1).replace("{x {x", "{ {", 1) + extra
        # print("<lilipond-"+CFG.OUTPUT_FOLDER+CFG.OUTPUT_PREFIX+self.agent.name+">\n"+l2)
        lilypond.to_pdf(
            l2, CFG.OUTPUT_FOLDER + CFG.OUTPUT_PREFIX + self.agent.name)
        self.agent.presence.set_presence(
            state=PresenceState(available=True, show=PresenceShow.AWAY))
        self.set_next_state(S_FINISHED)
Exemplo n.º 7
0
def export(melody_track, chords, key, time_sig, bpm, file):
    i = Instrument()
    i.instrument_nr = 1
    t2 = Track()
    for i in range(0, len(chords)):
        b = Bar(key, time_sig)
        if len(chords[i][0]) > 5:
            b.place_notes(None, 1)
        else:
            b.place_notes(NoteContainer(chords[i]), 1)
        t2 + b

    c = Composition()
    c.add_track(melody_track)
    c.add_track(t2)

    out_dir = 'out'

    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    mid = file.split('/')[-1]
    if os.path.exists(out_dir + '/' + mid):
        os.remove(out_dir + '/' + mid)
    MidiFileOut.write_Composition(out_dir + '/' + mid, c, bpm)

    file = out_dir + '/' + mid

    sys.argv.append('')
    sys.argv.append('')

    sys.argv[1] = "--midi-file=" + file
    sys.argv[2] = "--out-dir=" + out_dir

    midi.main()
    if os.path.exists(file):
        os.remove(file)
Exemplo n.º 8
0
from NoteGenerator import note_collection

# Constants

FIRST = 0
SECOND = 1
THIRD = 2
FOURTH = 3

# Prefix

pre = "test - "

# Start Composition

composition = Composition()
composition.set_author('Melody Nieun', '*****@*****.**')
composition.set_title('First Melody Composition with Python')

# Start a track (which will be a part of the composition defined above)
track = Track()

# Start a bar (which will be a part of the track defined above)
bar1 = Bar()


notes = note_collection(['C', 'D', 'E', 'F', 'G', 'A', 'B'])

# Generate the first note

generator = NoteGenerator(notes=notes, duration=4)#, conditions={0: condition1})
Exemplo n.º 9
0
Arquivo: song.py Projeto: tewe/canta
 def __init__(self):
     self.composition = Composition()
     self.path = ''
     self.song_name = ''
     self.bar_length = 16
Exemplo n.º 10
0
    def MIDI_to_Composition(self, file):
        (header, track_data) = self.parse_midi_file(file)
        c = Composition()
        if header[2]['fps']:
            print("Don't know how to parse this yet")
            return c
        ticks_per_beat = header[2]['ticks_per_beat']
        for track in track_data:
            t = Track()
            b = Bar()
            metronome = 1  # Tick once every quarter note
            thirtyseconds = 8  # 8 thirtyseconds in a quarter note
            meter = (4, 4)
            key = 'C'
            for e in track:
                (deltatime, event) = e
                duration = float(deltatime) / (ticks_per_beat * 4.0)
                if duration != 0.0:
                    duration = 1.0 / duration
                if deltatime != 0:
                    if not b.place_notes(NoteContainer(), duration):
                        t + b
                        b = Bar(key, meter)
                        b.place_notes(NoteContainer(), duration)

                if event['event'] == 8:
                    if deltatime == 0:
                        pass
                elif event['event'] == 9:

                # note on

                    n = Note(notes.int_to_note(event['param1'] % 12),
                             event['param1'] / 12 - 1)
                    n.channel = event['channel']
                    n.velocity = event['param2']
                    if len(b.bar) > 0:
                        b.bar[-1][2] + n
                    else:
                        b + n
                elif event['event'] == 10:

                # note aftertouch

                    pass
                elif event['event'] == 11:

                # controller select

                    pass
                elif event['event'] == 12:

                # program change

                    i = MidiInstrument()
                    i.instrument_nr = event['param1']
                    t.instrument = i
                elif event['event'] == 0x0f:

                # meta event Text

                    if event['meta_event'] == 1:
                        pass
                    elif event['meta_event'] == 3:

                    # Track name

                        t.name = event['data']
                    elif event['meta_event'] == 6:

                    # Marker

                        pass
                    elif event['meta_event'] == 7:

                    # Cue Point

                        pass
                    elif event['meta_event'] == 47:

                    # End of Track

                        pass
                    elif event['meta_event'] == 81:

                    # Set tempo warning Only the last change in bpm will get
                    # saved currently

                        mpqn = self.bytes_to_int(event['data'])
                        bpm = 60000000 / mpqn
                    elif event['meta_event'] == 88:

                    # Time Signature

                        d = event['data']
                        thirtyseconds = self.bytes_to_int(d[3])
                        metronome = self.bytes_to_int(d[2]) / 24.0
                        denom = 2 ** self.bytes_to_int(d[1])
                        numer = self.bytes_to_int(d[0])
                        meter = (numer, denom)
                        b.set_meter(meter)
                    elif event['meta_event'] == 89:

                    # Key Signature

                        d = event['data']
                        sharps = self.bytes_to_int(d[0])
                        minor = self.bytes_to_int(d[0])
                        if minor:
                            key = 'A'
                        else:
                            key = 'C'
                        for i in range(abs(sharps)):
                            if sharps < 0:
                                key = intervals.major_fourth(key)
                            else:
                                key = intervals.major_fifth(key)
                        b.key = Note(key)
                    else:
                        print('Unsupported META event', event['meta_event'])
                else:
                    print('Unsupported MIDI event', event)
            t + b
            c.tracks.append(t)
        return (c, bpm)
Exemplo n.º 11
0
from mingus.containers import Composition
from mingus.containers import Bar
from mingus.containers import Track
from mingus.containers import Note
import mingus.core.intervals as intervals

import mingus.extra.lilypond as LilyPond
from Mingus_LilyPond_helper import to_LilyPond_file
import track_functions as Track_Functions
from mingus.midi import midi_file_out
import copy
from EvolutionaryGenerator import EvolutionaryGenerator
import random as rnd

#Important variables!
fugue = Composition()
first_voice = Track()
second_voice = Track()


#input_key is a char signifying what key we are using
#input_subject is a Track, subject can be any length
def generate_fugue(key, subject):

    #If subject doesn't fill full bars fill out rest of last bar of subject with rest
    #if last bar is not full
    if not (subject[-1].is_full()):
        #place a rest at the end of the last bar with the length of 1/(remaining fraction of bar)
        subject[-1].place_rest(int(1.0 / subject[-1].space_left()))

    # Create first bar with subject in first voice and rest in second voice.
Exemplo n.º 12
0
def main():
    repo = Repo(sys.argv[1])
    factory = cf.ConverterFactory()
    converter = factory.get_converter("mod")
    curtime = datetime.datetime.now()
    if (len(sys.argv) == 3):
        target_file = sys.argv[2]
    else:
        target_file = "gitmelody" + str(curtime.year) + str(curtime.month) + str(curtime.hour) \
            + str(curtime.minute) + str(curtime.second) + ".mid"

    commits = list(repo.iter_commits('master'))

    timesignature = converter.getTimeSignature(commits)
    tsValue = timesignature[0] / timesignature[1]
    print(tsValue)
    print(timesignature)

    #nc = NoteContainer()
    bar = Bar()
    if timesignature != None:
        bar.set_meter((timesignature[0], timesignature[1]))
    t = Track()
    t2 = Track()
    dursum = 0
    tsValue = 1
    c = Composition()
    #durations are between 1 and 128
    for item in commits:
        #note_item = get_note_from_commit(item.stats.total)
        note_item = converter.getNoteFromCommit(item.stats.total)
        if (dursum + (1 / note_item[1]) <= tsValue):
            dursum = dursum + 1 / note_item[1]
            bar.place_notes(note_item[0], note_item[1])
        else:
            dursum = 0
            if (bar.space_left() > 0):
                booleanValue = bool(random.getrandbits(1))
                if booleanValue == True:
                    bar.place_notes(note_item[0], bar.space_left())
                else:
                    bar.place_rest(bar.space_left())
            t.add_bar(bar)
            second_line = converter.getChordOrArpeggio(bar)
            t2.add_bar(second_line)
            bar = Bar()
            bar.set_meter((timesignature[0], timesignature[1]))
    c.add_track(t)
    c.add_track(t2)
    print(bar.meter)

    #bar.place_notes(note_item[0], note_item[1])
    #t.add_notes(note_item[0])

    #print(item.stats.total['insertions'])
    #print(item.stats.additions)
    #print(item.stats.deletions)
    #print(item.stats.total)a

    #nc = NoteContainer(["A", "C", "E"])
    #midi_file_out.write_Track(target_file, t)
    midi_file_out.write_Composition(target_file, c)
Exemplo n.º 13
0
def generate_midi(instrument,
                  key,
                  chord_progression,
                  pad,
                  octave=None,
                  applause=False):
    composition = Composition()

    how_many_bars = 16

    # Make all these configurable
    # Or make them all random from a range
    track = Track(instrument, channel=1)

    drone_track = track_creator(pad, channel=2)
    # drone_track = track_creator("Pad4 (choir)", channel=2)

    # It's one of the few pitched drums
    timpani_track = track_creator("Timpani", channel=3)

    applause_track = track_creator("Applause", channel=4)

    bar = Bar(key, (4, 4))
    nc = NoteContainer("C", octave=2)
    bar.place_notes(nc, 1)
    applause_track.add_bar(bar)

    for _ in range(how_many_bars):

        # Can we get an index
        # We can with enumerate, but why do we want it
        for chord in chord_progression:
            # The Chord Progression

            bar = Bar(key, (4, 4))
            if not octave:
                octave = INSTRUMENT_OCTAVE.get(instrument.name, 4)

            for length in random.sample(CHORD_RHYTHMS, 1)[0]:
                some_notes = random.sample(chord,
                                           random.randint(1, len(chord)))
                nc = NoteContainer(some_notes, octave=int(octave))
                bar.place_notes(nc, length)
            track.add_bar(bar)

            drone_bar = Bar(key, (4, 4))
            nc = NoteContainer(chord[0], octave=2)
            drone_bar.place_notes(nc, 1)
            drone_track.add_bar(drone_bar)

            timpani_bar = Bar(key, (4, 4))
            nc = NoteContainer(key, octave=2)
            for length in [4, 4, 4, 4]:
                timpani_bar.place_notes(nc, length)
            timpani_track.add_bar(timpani_bar)

    composition.add_track(timpani_track, channel=5)
    composition.add_track(drone_track)
    composition.add_track(track)

    # Do we want to add the channel when adding or creating the track?
    if applause:
        composition.add_track(applause_track)

    instrument_name = MidiInstrument.names[instrument.instrument_nr]
    write_Composition(midi_file_name(instrument_name), composition, bpm=120)
Exemplo n.º 14
0
from mingus.containers import Note
from mingus.containers import NoteContainer
from mingus.containers import Bar
from mingus.containers import Track
from mingus.containers.instrument import Instrument, Piano, Guitar
from mingus.containers import Composition
from mingus.midi.midi_file_out import write_Composition

eb = Note("Eb", 4)
g = Note("G", 4)
bb = Note("Bb", 4)
n = NoteContainer([eb, g, bb])
c = Composition()
c.set_author('Dusty Carver', '*****@*****.**')
c.set_title('Late Nights')
t = Track(Guitar())
b = Bar('Eb', (4, 4))
b.place_notes(n, 4)
b.place_notes(n, 4)
b.place_notes(n, 4)
b.place_notes(None, 4)
t.add_bar(b)
c.add_track(t)

write_Composition("one.mid", c)