Ejemplo n.º 1
0
def test_readFile():
    
    comp = Composer(order = 3)   

    midi_file_folder = "../midifiles/classical_piano/c_maj/format0"
    
    paths = [os.path.join(midi_file_folder, f) for f in os.listdir(midi_file_folder)]
    paths = paths[:3]

    for path in paths: 
        midi = midi.readFile(path)
        # midi.quantize(32)

        print "Learning (" + path + ") ..."
        comp.learnFromMidi(midi)

    # print comp.marcovChains[1]

    midi = comp.getMidi(1, 1000)

    for e in midi.timedEventsList:
        print e

    samplerate = 44100
    bpm = 120
    numSamples = 60 * 44100
    out = []
    s = CSynth(samplerate) 

    it = iter(midi.timedEventsList)

    currentSample = 0
    # sample the last events was send to the synth at
    lastEventsSample = 0

    print "Rendering..."
    while currentSample < numSamples:
        try:
            nextEvents = it.next()
            
            # calculate samples between the two events
            nextEventsSample = nextEvents.sample(samplerate, midi.unitsPerBeat, bpm)

            sampleDiff = nextEventsSample - lastEventsSample
            currentSample += sampleDiff

            while sampleDiff > 0:
                if sampleDiff < BUFFER_SIZE:
                    out.extend(s.getSamplesBuffered(sampleDiff))
                    sampleDiff = 0
                else:
                    out.extend(s.getSamplesBuffered(min(sampleDiff, BUFFER_SIZE)))
                    sampleDiff -= BUFFER_SIZE


            for event in nextEvents.events:
                if event.type == Messages.NOTE_ON:
                    s.noteOn(event.note)
                if event.type == Messages.NOTE_OFF:
                    s.noteOff(event.note)

            lastEventsSample = nextEventsSample
        except StopIteration:
            break

    # render rest
    while currentSample < numSamples:
        if numSamples - currentSample > BUFFER_SIZE:
            out.extend(s.getSamplesBuffered(BUFFER_SIZE))
            currentSample += BUFFER_SIZE
        elif numSamples - currentSample > 0:
            out.extend(s.getSamplesBuffered(numSamples - currentSample))
            currentSample = numSamples
        else:
            break



    print "Writing to file..."
    inout.writeMono("/tmp/asdf_python.wav", out, 44100)