gpt4 book ai didi

python-3.x - VLC音频播放器结束时如何突破python输入?

转载 作者:行者123 更新时间:2023-12-03 00:25:09 26 4
gpt4 key购买 nike

我正在尝试使用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

...

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()

关于python-3.x - VLC音频播放器结束时如何突破python输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60905066/

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