我正在尝试使用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()
问题是由于playSong
循环,当player
完成歌曲时while True
方法不会退出。程序卡在
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
sel = selectors.DefaultSelector()
...
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.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_length() == 0 or player.get_time() < player.get_length():
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()