Python Forum

Full Version: Exit Function - loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi , i'm actually coding a midi looper on raspberry pi.
I have a usb midi interface thar receive midi message (and send them to hardware synth) and a midi footswhich that send midi message to control the looper.

outport = mido.open_output('MIDISPORT 2x2 Anniv:MIDISPORT 2x2 Anniv MIDI 1 28:0')
songlist = (glob.glob("/home/pi/Documents/song/*.mid"));

#Function that play the midi file in loop 
def songplay(song):
    with outport as output:
        try:
            midifile = MidiFile(song)
            while True:
                for message in midifile.play():    
                    output.send(message)
    
 
#HERE THE CODE THAT LISTEN TO INCOMING MIDI MESSAGE(IF NOTE 36 CHOOSE THE MIDI FILE TO PLAY IN A LIST)(IF NOTE 27 PLAY THE SELECTED FILE)
try:
    with mido.open_input('arduino_midi:arduino_midi MIDI 1 20:0') as port:
        for message in port:
            if message.type in ('note_on') and message.note == 36:
                print(songlist[i])
                if i == (nbrsong-1):
                    i = 0
                else:
                    i += 1
           
            if message.type in ('note_on') and message.note == 37:
                songplay(songlist[i])

            if message.type in ('note_on') and message.note == 38:
                HOW TO STOP THE FONTION ???
It works but when the file is playing (when we are in the function) the instructions from the try doesn't work anymore. I'd like for add incoming message ex. IF note 38 = Stop playing the song... I don't know if the "try" is the good solution
Does this work right?

def songplay(song):
    with outport as output:
        try:
            midifile = MidiFile(song)
            while True:
                for message in midifile.play():    
                    output.send(message)
(Sep-17-2020, 08:05 AM)cnull Wrote: [ -> ]Does this work right?

def songplay(song):
    with outport as output:
        try:
            midifile = MidiFile(song)
            while True:
                for message in midifile.play():    
                    output.send(message)

Yes, in fact his is the code, actuall I have an expet KeyboardInterrupt ... but yes it Works

def songplay(song):
    with outport as output:
        try:
            midifile = MidiFile(song)
            while True:
                for message in midifile.play():    
                    output.send(message)
 
        except KeyboardInterrupt:
            print()
            output.reset()