[英]How to make delay in python without stopping the rest of the program
I am redesigning a program that basically plays sound on command.我正在重新设计一个基本上按命令播放声音的程序。 I am trying to find a way to shuffle a list of songs.
我试图找到一种方法来随机播放歌曲列表。 I have the basic idea of what should happen but i can't seem so find a way for it to work.
我对应该发生的事情有一个基本的想法,但我似乎无法找到让它起作用的方法。
I have tried stuff like 'time.sleep(1)' and '.after(miliseconds, function)'.我尝试过诸如“time.sleep(1)”和“.after(miliseconds, function)”之类的东西。
songlist = [["SongName","SongFileName",{length of song in miliseconds}],
["SongName2","SongFileName2",{length of song in miliseconds}]]
def shuffle():
shuffle=True
while shuffle == True:
song=random.choice(songlist)
song2 =random.choice(songlist)
while song==song2:
song2=random.choice(songlist)
label2.config(text=song[0])
winsound.PlaySound(song[1], winsound.SND_ASYNC)
window.after(song[2])
What i want to happen is for it to play random songs from the song list until the "stop" button is pressed (Stop button not shown in code)我想要发生的是让它从歌曲列表中随机播放歌曲,直到按下“停止”按钮(停止按钮未显示在代码中)
Just to give you some place to start.只是为了给你一些开始的地方。 This would give you a random song from the list.
这将为您提供列表中的随机歌曲。
songlist = ['a', 'b', 'c']
def shuffle():
while True:
for s in songlist:
song=random.choice(s)
print(song)
if __name__ == '__main__':
shuffle()
One thing you could try, is to use threads.您可以尝试的一件事是使用线程。 so first import thread module:
所以首先导入线程模块:
Python2.7: from thread import start_new_thread
Python3.x: import threading
then you just call your method that you want run "parallel" to your wait function, in your case a "playSong"-method:然后你只需调用你想要与你的等待函数“并行”运行的方法,在你的情况下是一个“playSong”方法:
Python2.7: start_new_thread(playSong, ())
Python2.7:
start_new_thread(playSong, ())
Python3.x: Python3.x:
t = threading.Thread(target=playSong)
t.start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.