在python3中,如何正确地迫使程序在播放完歌曲之前循环



我正在用python3编写一个虚拟助手。我有一个while循环,播放两首随机选择的歌曲。我按ctrl c键跳到下一首歌。这是一个很长很长的if语句的一部分。一旦歌曲开始,我可以点击ctrl c进入下一首歌,但在最后一首歌结束后,程序就卡住了。我需要再次按下ctrl 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。

修复它:

# 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

相关内容

  • 没有找到相关文章

最新更新