В python3, как правильно заставить мою программу перемещаться по al oop до того, как она закончит воспроизведение песни? - PullRequest
0 голосов
/ 20 апреля 2020

Я пишу виртуального помощника в python3. У меня есть время l oop, которое воспроизводит две случайно выбранные песни. Я нажимаю Ctrl c, чтобы перейти к следующей песне. Вот часть длинного, длинного оператора if. Как только песни начинаются, я могу go перейти к следующей песне, нажав Ctrl c, но после окончания последней песни программа застревает. Мне нужно снова нажать Ctrl c, чтобы он продолжался. Кстати, когда играет musi c, микрофон перестает работать, и это нормально, но это означает, что я не могу кричать «стоп» или «следующий», поэтому нажатие клавиши кажется наиболее подходящим.

# next command
    elif 'music' in command:
        if playcounter == 1:
            talktome.talkToMe("Choosing random song . . . ")
        with open('/home/bard/Code/Juliet/mymusiclist.txt') as f:
            if playcounter == 1:
                print("Total songs to play " + str(totalsongstoplay) + ".")
            mymusic = f.read().splitlines()
            random_index = randrange(len(mymusic))
            song = mymusic[random_index]
            print("Playing song number " + str(playcounter) + ".")
            print("Song file:")
            print(song)
            playthis = 'mpg123 -q ' + song
            #subprocess.call(playthis, shell=True)
            p1=subprocess.Popen(playthis, shell=True)
            try:
                #while True:
                while p1.poll is not None:
                    pass
            except KeyboardInterrupt:
                # Ctrl-C was pressed (or user knew how to send SIGTERM to the python process)
                pass # not doing anything here, just needed to get out of the loop
            # nicely ask the subprocess to stop
            p1.terminate()
            # read final output
            sleep(1)
            # check if still alive
            if p1.poll() is not None:
                print('had to kill it')
                p1.kill()
            #end new code
            if playcounter < totalsongstoplay:
                playcounter = playcounter + 1
                assistant(command, playcounter, totalsongstoplay)
            else:
                playcounter=1
# next command

Спасибо. Полный проект на https://github.com/MikeyBeez/Juliet Кстати, этот голосовой активированный ассистент выполняет всю свою речь, чтобы текст локально - ничего в облаке. Я нахожусь на Ubuntu 18.04, и я использую Conda для моей виртуальной среды. Python - это 3.6.1.

1 Ответ

0 голосов
/ 20 апреля 2020

Исправлено:

# next command
    elif 'music' in command:
        if playcounter == 1:
            talktome.talkToMe("Choosing random song . . . ")
        with open('/home/bard/Code/Juliet/mymusiclist.txt') as f:
            if playcounter == 1:
                print("Total songs to play " + str(totalsongstoplay) + ".")
            mymusic = f.read().splitlines()
            random_index = randrange(len(mymusic))
            song = mymusic[random_index]
            print("Playing song number " + str(playcounter) + ".")
            print("Song file:")
            print(song)
            playthis = 'mpg123 -q ' + song
            p1=subprocess.Popen(playthis, shell=True)
            try:
                #while True:
                while p1.poll() is None:
                    pass
                #p1.wait()
            except KeyboardInterrupt:
                # Ctrl-C was pressed (or user knew how to send SIGTERM to the python process)
                pass # not doing anything here, just needed to get out of the loop
            # nicely ask the subprocess to stop
            p1.terminate()
            # read final output
            sleep(1)
            # check if still alive
            if p1.poll() is not None:
                print('had to kill it')
                p1.kill()
            #end new code
            if playcounter < totalsongstoplay:
                playcounter = playcounter + 1
                assistant(command, playcounter, totalsongstoplay)
            #end if 
            playcounter = 1
...