VLC 音频播放器结束时如何中断 python 输入?

How to break out of python input when VLC audio player ends?

我正在尝试使用 python-vlc 在 Python3 中制作一个音乐播放程序来播放音频文件。只要歌曲没有结束,我就希望能够暂停和播放音频。我有一个 playSong(path) 函数可以从给定路径播放音频文件,还有一个 main 方法可以在我指定的任何歌曲路径上调用 playAudio 函数。我还有一些其他功能可以使用 youtube-dl 从 YouTube 下载歌曲。 main 或任何其他方法都没有问题。问题出在 playSong 函数中。

这是我的代码:

import os
import re
import sys
import random
import vlc
import ytUrl
import youtube_dl
from termcolor import colored
from mutagen.mp3 import MP3

...

def playSong(path):
    audio = MP3(path)
    duration = audio.info.length  # This is not in use as of right now
    player = vlc.MediaPlayer(path)
    player.audio_set_delay(1000)  # keeps vlc from playback freezing issues
    player.play()
    print("Playing " + colored(path[:-len(".mp3")], "green") + "...")

    # the problem is here
    while True:
        do = input("> ").lower()
        if do == "pause":
            player.pause()
        elif do == "play":
            player.play()
        elif do == "stop" or do == "skip":
            player.stop()
        elif do == "exit":
            player.stop()
            main() 

问题是while True循环导致player播放完歌曲后playSong方法不会退出。程序卡在

do = input("> ").lower()

即使玩家已经完成。我不能只删除 while 循环,因为我希望能够一直播放和暂停这首歌!

我应该如何解决这个问题?感谢您的帮助!

这适用于我 Ubuntu。我相信它也适用于 Mac 但不适用于 Windows:

import os
import re
import selectors
import sys
import random
import vlc
import ytUrl
import youtube_dl
from termcolor import colored
from mutagen.mp3 import MP3

...

def playSong(path):
    audio = MP3(path)
    duration = audio.info.length  # This is not in use as of right now
    player = vlc.MediaPlayer(path)
    player.audio_set_delay(1000)  # keeps vlc from playback freezing issues
    player.play()
    print("Playing " + colored(path[:-len(".mp3")], "green") + "...")

    sel = selectors.DefaultSelector()
    sel.register(sys.stdin.fileno(), selectors.EVENT_READ)

    while True:
        sys.stdout.write('> ')
        sys.stdout.flush()
        # Poll for command input as long as the player hasn't reached the end
        while player.get_state() != vlc.State.Ended:
            if sel.select(0.1):
                break  # Input avaliable - time to read input, so stop polling
        else:
            break  # Quit the command handling loop
        do = input().lower()
        if do == "pause":
            player.pause()
        elif do == "play":
            player.play()
        elif do == "stop" or do == "skip":
            player.stop()
        elif do == "exit":
            player.stop()
            main()

while True:while player.is_playing == 1: 交换,从而在歌曲结束时退出循环。