gpt4 book ai didi

python-3.x - 如何使用键盘暂停/中断

转载 作者:行者123 更新时间:2023-12-03 01:38:49 26 4
gpt4 key购买 nike

我正在使用以下脚本来播放当前路径中的所有WAV文件。我将对其进行修改以打印一些文本文件的输出。这部分很容易。

需要知道播放WAV文件的循环中的方式/位置,在何处添加一些代码以使用键盘暂停/中断代码的执行。

#!/usr/bin/python3

import vlc
import time
import glob

wav_files = glob.glob("*.wav")
instance=vlc.Instance(["--no-sub-autodetect-file"])

# You should not recreate a player for each file, just reuse the same
# player
player=instance.media_player_new()

for wav in wav_files:
player.set_mrl(wav)
player.play()
playing = set([1,2,3,4])
time.sleep(5) #Give time to get going
duration = player.get_length() / 1000
mm, ss = divmod(duration, 60)
print("Playing", wav, "Length:", "%02d:%02d" % (mm,ss))
while True:
state = player.get_state()
if state not in playing:
break
continue

最佳答案

getch中窃取vlc.py由于您未指定操作系统,因此我添加了Windows选项。

#!/usr/bin/python3

import vlc
import time
import glob
import sys
import termios, tty

try:
from msvcrt import getch # try to import Windows version
except ImportError:
def getch(): # getchar(), getc(stdin) #PYCHOK flake
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return ch

wav_files = glob.glob("*.wav")
print("Play List")
for f in wav_files:
print(f)
instance=vlc.Instance(["--no-sub-autodetect-file"])

# You should not recreate a player for each file, just reuse the same
# player
player=instance.media_player_new()

for wav in wav_files:
player.set_mrl(wav)
player.play()
playing = set([1,2,3,4])
time.sleep(1) #Give time to get going
duration = player.get_length() / 1000
mm, ss = divmod(duration, 60)
print("Playing", wav, "Length:", "%02d:%02d" % (mm,ss))
while True:
state = player.get_state()
if state not in playing:
break
k = getch()
if k in ["N","n"]:#Next
player.stop()
break
elif k in ["Q","q"]:#Quit
player.stop()
sys.exit()
break
elif k == " ":#Toggle Pause
player.pause()
else:
print("[Q - Quit, N - Next, Space - Pause]")
continue

关于python-3.x - 如何使用键盘暂停/中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49228192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com