python - 如果用户未按下任何键,如何自动播放播放列表中的下一首歌曲?
问题描述
我想为用户提供播放、暂停、播放下一首或上一首歌曲的选项。如果用户没有按下任何按钮,列表中的下一首歌曲应该会自动播放。目前,该程序因用户输入而暂停。
我尝试在另一个线程中播放歌曲并等待用户在主线程中输入选择。但问题是主线程在播放下一首歌曲之前等待用户的输入。
def music(file):
pygame.mixer.music.load(file)
pygame.mixer.music.play()
try:
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(0)
except:
pass
def pause():
print(file + " paused")
pygame.mixer.music.pause()
global set
set = 1
def playsong():
global set
global t1
print ("Playing song named : " + file)
if file != "" and set==0:
t1 = threading.Thread(target = music ,args=(file,))
t1.setName("audio bajao")
t1.start()
ch = 1
song_list = ["song1.mp3","song2.mp3"]
while((i < len(song_list)) and (ch != 5) ):
ch = input("Enter choice ")
file = song_list[i]
if(ch == 1):
playsong()
elif(ch == 2):
ch = 1
pause()
elif(ch == 3):
#play previous song
ch = 1
i -= 2
elif (ch == 4):
#play next song
ch = 1
elif (ch == 5):
break
i += 1
如果用户未按下任何键,我希望程序在歌曲结束时播放列表中的下一首歌曲。它不应该再次要求用户按下播放键来播放下一首歌曲。
解决方案
你可以试试pygame.mixer.get_busy()
为了实现这一点,添加某种计时器变量,我个人更喜欢滴答计数器,所以......
inactive_ticks = 0
之后,在您的主事件循环中,用于pygame.mixer.get_busy()
检查是否正在播放音乐,然后...
if not pygame.mixer.get_busy():
inactive_ticks += 1
if inactive_ticks == 100:
# Play the next song
inactive_ticks = 0
那应该行得通。
推荐阅读
- mysql - 是否可以按 15 分钟间隔获取事务和组的总数
- c - 如何在 DPDK 中生成增量数据值
- sql - 无法批量加载,因为文件 ... 无法打开。操作系统错误代码58(指定的服务器无法执行请求的操作)
- mysql - Docker Compose 中的 Mysql 没有使用环境变量
- python-3.x - 从不同进程导入 Tensorflow 2.0 gpu
- jquery-select2 - 在按钮单击时设置 ng-select2 的值
- c++ - 如何在给定时钟偏移的情况下正确获取时间
- javascript - html中的粘性图像占用标题中的空间
- makefile - 如何从标准输入读取到生成文件变量
- java - 如何为另一个构造函数的类中的类创建字段数组引用