Exemple #1
0
    def playMeasure(self, song_name, measure_num=0, tempo=120):
        measure = MIDIFile(1)
        track, time, channel = 0, 0, 0
        measure.addTrackName(track, time, "Measure")
        measure.addTempo(track, time, tempo)

        # Add notes to measure.
        for note in self:
            pitch = note.pitch
            duration = note.getDuration()
            time = note.getTime()
            volume = note.getVolume()
            measure.addNote(track, channel, pitch, time, duration, volume)
        measure_num = str(measure_num)

        # Write the song to a file.
        os.system("touch .songs/" + song_name + "/measure" + measure_num +
                  ".mid")
        binfile = open(
            ".songs/" + song_name + "/measure" + measure_num + ".mid", 'wb')
        measure.writeFile(binfile)
        binfile.close()
        os.system("fluidsynth -i " + felixNamespace.fluidsynthPath +
                  " .songs/" + song_name + "/measure" + measure_num +
                  ".mid > .dump")
Exemple #2
0
 def playSong(self):
     the_song = MIDIFile(1)  # Note: 1 here is the number of tracks.
     time = 0  # Initialize time
     track = 0
     the_song.addTrackName(track, time, self.song_name)  # Track = 0
     the_song.addTempo(track, time, 120)  # 120 is the tempo.
     for measure in self.measures:
         for note in measure:
             the_song.addNote(track, note.getChannel(), note.getPitch(),
                              time + note.getTime(), note.getDuration(),
                              note.getVolume())
         time += 4
     song_file = open(
         ".songs/" + self.song_name + "/" + self.song_name + ".mid", "wb")
     the_song.writeFile(song_file)
     song_file.close()
     os.system("fluidsynth -i " + felixNamespace.fluidsynthPath +
               " .songs/" + self.song_name + "/" + self.song_name +
               ".mid > .dump")
Exemple #3
0
    def __init__(self, number_tracks=1, tempo=60, instrument=0, channel=None):
        """
        instrument: can be an integer or a list
        channel: can be an integer or a list
        """

        self.number_tracks = number_tracks
        self.midi_data = MIDIFile(number_tracks)

        for track in range(number_tracks):
            self.midi_data.addTrackName(track, 0, "Track {0}".format(track))
            self.midi_data.addTempo(track, 0, tempo)
            instr = instrument[track] if isinstance(instrument, list) else instrument
            if channel is None:
                _channel = track
            elif isinstance(channel, list):
                _channel = channel[track]
            else:
                _channel = channel
            self.midi_data.addProgramChange(track, _channel, 0, instr)
Exemple #4
0
def save_to_file(filename, consolidated):
    midi = MIDIFile(1)

    track = 0
    channel = 0
    total_beats_so_far = 0

    midi.addTempo(track, total_beats_so_far, _beats_per_minute)
    for c in consolidated:
        start = total_beats_so_far
        duration = _beats_per_window * c['windows']
        volume = 100
        pitch = find_midi_pitch_by_frequency(c['frequency'])
        midi.addNote(track, channel, pitch, total_beats_so_far, duration,
                     volume)
        print 'add note', pitch, total_beats_so_far, duration

        total_beats_so_far += duration

    handler = open(filename, 'wb')
    midi.writeFile(handler)
    handler.close()
Exemple #5
0
overrides = {}
showProgress = False
midiVelocity = 64
for override in sys.argv[1:-2]:
    p = override.split(":")
    if (p[0] == "showprogress"): showProgress = True
    elif (p[0] == "midivelocity"): midiVelocity = int(p[1])
    else: overrides[p[0]] = p[1]

if (showProgress):
    NamedWindow("Main")
    ResizeWindow("Main", 640, 480)

cap = CaptureFromFile(sys.argv[len(sys.argv)-1])
scanner = KeyboardScanner(QueryFrame(cap), overrides)
midi = MIDIFile(1)

midi.addTrackName(0,0,"Transcribed from Synthesia")
midi.addTempo(0,0,120.0)

noteDeltas = {}
while True:
    t = GetCaptureProperty(cap, CV_CAP_PROP_POS_MSEC) / 500.0
    print t, "\r",
    frame = QueryFrame(cap)
    if (frame == None): break
    changes = scanner.scanFrame(frame)
    if (showProgress):
        ShowImage("Main", scanner.debugImage)
        WaitKey(1)
    for pitch in changes:
def ptcop2midi(ptcop, outfile):

    midi = MIDIFile(200)

    print ptcop2midi_beat(8160)

    for i, unit in enumerate(ptcop.units):

        channel = 0
        track = i

        midi.addTrackName(i, channel, unit.name)
        midi.addTempo(i, channel, int(sys.argv[2]))

        note = 80
        velocity = 104
        porta = 0

        bend = 0x4000 / 2

        for e in unit.events:

            beat = ptcop2midi_beat(e.position)

            if e.type == pxtone.EventType.VOICE:

                # track = e.value
                velocity = e.value

            elif e.type == pxtone.EventType.ON:

                # find all note events in the range of
                # (beat, ptcop2midi_beat(e.value))

                notes = unit.notes_between(e.position, e.position + e.value)

                if not notes:
                    midi.addNote(track, channel, note, beat,
                                 max(ptcop2midi_beat(e.value) - 0.001, 0.001),
                                 velocity)
                else:

                    if notes[0].position != e.position:
                        midi.addNote(
                            track, channel, note, beat,
                            ptcop2midi_beat(notes[0].position - e.position),
                            velocity)

                    j = 0
                    l = len(notes) - 1

                    while j < l:

                        midi.addNote(
                            track, channel, ptcop2midi_note(notes[j].value),
                            ptcop2midi_beat(notes[j].position),
                            ptcop2midi_beat(notes[j + 1].position -
                                            notes[j].position), velocity)

                        j += 1

                    midi.addNote(
                        track, channel, ptcop2midi_note(notes[-1].value),
                        ptcop2midi_beat(notes[-1].position),
                        max(
                            ptcop2midi_beat(e.position + e.value -
                                            notes[-1].position) - 0.001,
                            0.001), velocity)

            elif e.type == pxtone.EventType.VELOCITY:

                # velocity = e.value
                pass

            elif e.type == pxtone.EventType.NOTE:

                note = ptcop2midi_note(e.value)

            elif e.type == pxtone.EventType.KEY_PORTA:

                midi.addPitchBendEvent(track, channel, beat, e.value)

            # elif e.type == pxtone.EventType.VOLUME:

            #     midi.addControllerEvent(track,
            #                             channel,
            #                             beat,
            #                             MIDIEvents.VOLUME,
            #                             e.value)

            # elif e.type == pxtone.EventType.PAN:

            #     midi.addControllerEvent(track,
            #                             channel,
            #                             beat,
            #                             MIDIEvents.PAN,
            #                             e.value)

    out = open(outfile, 'wb')
    midi.writeFile(out)
    out.close()
Exemple #7
0
def ptcop2midi(ptcop, outfile):

    midi = MIDIFile(len(ptcop.units))

    for i, unit in enumerate(ptcop.units):

        channel = 0

        midi.addTrackName(i, channel, unit.name)
        midi.addTempo(i, channel, ptcop.tempo)

        note = 80
        velocity = 104
        porta = 0

        bend = 0x4000 / 2

        for e in unit.events:

            beat = ptcop2midi_beat(e.position)

            if e.type == pxtone.EventType.ON:

                midi.addNote(i, channel, note, beat, ptcop2midi_beat(e.value),
                             velocity)

            elif e.type == pxtone.EventType.VELOCITY:
                velocity = e.value

            elif e.type == pxtone.EventType.NOTE:

                note = ptcop2midi_note(e.value)

                on = unit.on(e.position)

                if on:

                    if on.position == e.position:

                        # reset pitch bend
                        if bend != 0x4000 / 2:
                            bend = 0x4000 / 2
                            midi.addPitchBendEvent(i, channel, beat, bend)

                    else:

                        # glissando

                        # on what note did the "on" begin?
                        old_note = unit.note_before(e.position)
                        old_note = ptcop2midi_note(old_note)

                        # semitones to travel
                        diff = note - old_note

                        # where the pitch bend should wind up
                        target = 0x4000 / 2 + diff * 0x4000 / (
                            PITCH_BEND_SEMITONES * 2)

                        print porta, target

                        midi.addPitchBendEvent(i, channel, beat, bend)
                        midi.addPitchBendEvent(i, channel,
                                               beat + ptcop2midi_beat(porta),
                                               target)

                        bend = target

            elif e.type == pxtone.EventType.KEY_PORTA:

                porta = e.value

            # elif e.type == pxtone.EventType.VOLUME:

            #     midi.addControllerEvent(i,
            #                             channel,
            #                             beat,
            #                             MIDIEvents.VOLUME,
            #                             e.value)

            # elif e.type == pxtone.EventType.PAN:

            #     midi.addControllerEvent(i,
            #                             channel,
            #                             beat,
            #                             MIDIEvents.PAN,
            #                             e.value)

    out = open(outfile, 'wb')
    midi.writeFile(out)
    out.close()
def midiExport(liveSet, midiFilePath, separateChannels=False):

    print('Init Midi Export')
    # How Many Midi Tracks in liveSet?
    usedMidiTrack = 0
    for track in liveSet.tracks:
        if len(track.notes) != 0:
            usedMidiTrack += 1
    #print ("Used Midi Track count:", usedMidiTrack)

    # Create the MIDIFile Object with 1 track
    MyMIDI = MIDIFile(len(liveSet.tracks), file_format=1, adjust_origin=True)

    i = 0
    for track in liveSet.tracks:
        # Tracks are numbered from zero. Times are measured in beats.
        if track.midiExport:  #len(track.notes) != 0 and
            trackId = i
            channel = i % 16 if separateChannels else 0
            time = 0

            # Add track name.
            name = str(track.name)
            MyMIDI.addTrackName(trackId, time, name)

            # Add tempo Map to first track.
            if trackId == 0:
                events = getAutomationEvents(liveSet.tempoMap)
                for event in events:
                    MyMIDI.addTempo(trackId, event['Time'], event['Value'])

            # Add Notes.
            for note in track.notes:
                pitch = note.pitch
                time = note.start
                duration = note.duration
                volume = note.velocity

                MyMIDI.addNote(trackId, channel, pitch, time, duration, volume)

            # Add Clip Automations to MidiTrack
            for clip in track.arrangementClips:
                for envelope in clip.envelopes:
                    events = getAutomationEvents(envelope.events)
                    target = envelope.targetName
                    for event in events:
                        time = event['Time'] + clip.startTime - clip.loopStart
                        value = int(event['Value'])
                        #print('time:{}, value:{}'.format(time, value))

                        if target == 'Pitch Bend':
                            MyMIDI.addPitchWheelEvent(trackId, channel, time,
                                                      value)
                            print(time, value)
                        elif target == 'Channel Pressure':
                            MyMIDI.addChannelPressureEvent(
                                trackId, channel, time, value)

                        # Prevent CC7(Volume) and CC10(Pan) Conflicts
                        elif int(target) != 7 and int(target) != 10:
                            MyMIDI.addControllerEvent(trackId, channel, time,
                                                      int(target), value)

                        if isinstance(target, int) and int(
                                target) == 7 and not track.volumeMidiExport:
                            MyMIDI.addControllerEvent(trackId, channel, time,
                                                      int(target), value)

                        if isinstance(target, int) and int(
                                target) == 10 and not track.panMidiExport:
                            MyMIDI.addControllerEvent(trackId, channel, time,
                                                      int(target), value)

            i += 1

            # Add Volume Automation to Track
            if track.volumeMidiExport:
                events = getAutomationEvents(track.volumeAutomationEvents)
                for event in events:
                    time = event['Time']
                    value = event['Value']

                    # Scale value [0, 1] to [0, 100] and [1, 2] and [100, 127]
                    if value <= 1:
                        value = int(value * 100)
                    else:
                        value = int(100 + value * 28 / 2)
                    #print('time:', time, 'value:', value)
                    MyMIDI.addControllerEvent(trackId, channel, time, 7, value)

            # Add Pan Automation to Track
            if track.panMidiExport:
                events = getAutomationEvents(track.panAutomationEvents)
                for event in events:
                    time = event['Time']
                    value = event['Value']
                    # Scale value [-1, 1] to [0, 127]
                    value = int((value + 1) * 64)
                    MyMIDI.addControllerEvent(trackId, channel, time, 10,
                                              value)

    # And write it to disk.
    binfile = open(midiFilePath, 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
    print('Midi Export Done')
Exemple #9
0
def ptcop2midi(ptcop, outfile):

    midi = MIDIFile(200)


    for i, unit in enumerate(ptcop.units):

        channel = 0
        track = i

        midi.addTrackName(i, channel, unit.name)
        midi.addTempo(i, channel, int(sys.argv[2]))

        note = 80
        velocity = 104
        porta = 0

        bend = 0x4000/2

        for e in unit.events:

            beat = ptcop2midi_beat(e.position)

            if e.type == pxtone.EventType.VOICE:

                track = e.value
                # pass

            elif e.type == pxtone.EventType.ON:
                
                midi.addNote(track, 
                             channel,
                             note,
                             beat + PADDING,
                             ptcop2midi_beat(e.value) - PADDING,
                             velocity)

            elif e.type == pxtone.EventType.VELOCITY:
                velocity = e.value

            elif e.type == pxtone.EventType.NOTE:

                note = ptcop2midi_note(e.value)

                on = unit.on(e.position)

                if on:

                    if on.position == e.position:

                        # reset pitch bend
                        if bend != 0x4000/2:
                            bend = 0x4000/2
                            midi.addPitchBendEvent(track, channel, ptcop2midi_beat(on.position) + PADDING, bend);
                        pass

                    else:

                        # glissando
                    
                        # on what note did the "on" begin?
                        old_note = unit.note_before(e.position)
                        old_note = ptcop2midi_note(old_note)

                        # semitones to travel
                        diff = note - old_note

                        if diff > PITCH_BEND_SEMITONES:
                            diff = PITCH_BEND_SEMITONES
                        elif diff < -PITCH_BEND_SEMITONES:
                            diff = -PITCH_BEND_SEMITONES

                        # where the pitch bend should wind up
                        target = 0x4000/2 + diff * 0x4000 / (PITCH_BEND_SEMITONES*2) 

                        # print porta, target

                        startbeat = beat
                        if startbeat == midi2ptcop_beat(on.position):
                            startbeat += PADDING

                        endbeat = beat + ptcop2midi_beat(porta)
                        end = midi2ptcop_beat(on.position + on.value)
                        
                        if endbeat >= end:
                            shortened = end - PADDING
                            target = map(shortened, startbeat, endbeat, bend, target)
                            endbeat = shortened

                        # if endbeat >= beat:
                        midi.addPitchBendEvent(track, channel, startbeat, bend);
                        midi.addPitchBendEvent(track, channel, endbeat, target);

                        bend = target
                        
            elif e.type == pxtone.EventType.KEY_PORTA:

                porta = 0 #e.value

            # elif e.type == pxtone.EventType.VOLUME:

            #     midi.addControllerEvent(track,
            #                             channel,
            #                             beat,
            #                             MIDIEvents.VOLUME,
            #                             e.value)

            # elif e.type == pxtone.EventType.PAN:


            #     midi.addControllerEvent(track,
            #                             channel,
            #                             beat,
            #                             MIDIEvents.PAN,
            #                             e.value)



    out = open(outfile, 'wb')
    midi.writeFile(out)
    out.close()
'''
Created by: Brian Richard, Jonathan Zhang, Aneel Yelamanchili
on July 28 2014
[email protected], [email protected], [email protected]
'''

from MidiFile import MIDIFile
import song_maker, GUI

#builds a midi, melody, and three harmonies
midi1 = MIDIFile(1)
mel1 = song_maker.Melody(4)
harm = song_maker.Harmony(mel1)
mel1.buildNotes()
harm.buildNotes()
harm.buildNotes()
harm.buildNotes()

mel1.buildMelody(midi1)
harm.buildHarmony(midi1)

#writes to MIDI file
with open('output.mid', 'wb') as my_file:
    midi1.writeFile(my_file)

melDuration = []
melNotes = []

harmDuration = []
harm1Notes = []
harm2Notes = []