我想用python(不使用任何花哨的GUI,只是基本的命令行)創建MP3Player。您可以輸入命令,如打印所有歌曲的「播放列表」或播放播放列表中播放指定歌曲的「播放[num]」。我可以在一個線程中完成這一切,但我想要的是創建另一個線程,以便在實際播放音樂的同時可以執行更多命令,如「添加歌曲」或「刪除歌曲」(而不是等待音樂完成)。以下是我有一個線程:Python MP3Play與線程
import mp3play, time
clip = mp3play.load(song)
clip.play()
time.sleep(clip.seconds()) #Waits the duration of the song
clip.stop()
#Command line asks for input after this
這工作都很好,很正常,但是當我嘗試實施穿入到這一點,就像這樣:
import mp3play, time
def play(songname):
clip = mp3play.load(song)
clip.play()
time.sleep(clip.seconds()) #Waits the duration of the song
clip.stop()
#Get user input here
#Check if user inputted command
#User inputed "play"
thread.start_new_thread(play,("some_random_song.mp3",))
它毛刺出來。這一切似乎都很好,直到你通過歌曲中途關閉應用程序並且音樂仍然繼續運行。要停止音樂,我必須打開任務管理器並結束任務。於是我想到了有「停止」命令,以及,這不會關閉線程,但它會使用
clip.stop()
我不知道,如果你試圖阻止()的ISN剪輯會發生什麼沒有運行,所以我實現了一個預防系統(布爾運行,檢查它是否)。但現在沒有什麼作品,迄今爲止這裏是我的代碼:
def play(filename):
global clip
clip.play()
time.sleep(clip.seconds())
clip.stop()
playing = False
clip = ""
#Get user input
#blah blah blah command stuff
#User inputted "play"
thread.start_new_thread(play,("some_random_song.mp3",))
playing = True
#Goes back to command line
#User inputted 'stop' this time
if playing:
clip.stop()
playing = False
但是當我嘗試運行此,它得到clip.play()的線程,但犯規啓動它。我不知道如何解決這個問題,如果可以不用線程就可以做到這一點。提前致謝。
當我鍵入「玩」它開始播放音樂,但它並沒有顯示指針「>」要求的下一個命令(即線程被捆綁起來'sleep'ing爲mp3play'clip')。難道我做錯了什麼? –