如何暂停/中断键盘

时间:2018-03-12 04:31:23

标签: python-3.x audio wav vlc

我正在使用以下脚本播放当前路径中的所有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

1 个答案:

答案 0 :(得分:0)

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