如何用键盘 pause/interupt

How to pause/interupt with keyboard

我正在使用以下脚本来播放当前路径中的所有 WAV 文件。我将修改它以打印一些文本文件的输出。那部分很简单。

需要知道 how/where 在播放 WAV 文件的循环中,在哪里添加一些代码 pause/interupt 使用键盘执行代码。

#!/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

vlc.py
中偷走 getch 我添加了 windows 选项,因为您没有指定 OS.

#!/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