Python Forum
Exit Function - loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Exit Function - loop (/thread-29717.html)



Exit Function - loop - Tetsuo30 - Sep-17-2020

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


RE: Exit Function - loop - cnull - Sep-17-2020

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)



RE: Exit Function - loop - Tetsuo30 - Sep-17-2020

(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()