playsound是一個很簡單的庫
from playsound import playsound # 導包
playsound('path') # 播放path下的音頻檔案
但直接執行playsound播放,會占用主執行緒
但是搭配上python自帶的Thread庫,就能讓音樂播放器在后臺運行
import threading
from playsound import playsound # 導包
def cycle(path): # 回圈播放
while 1:
playsound(path)
def play(path,cyc=False): # 播放
if cyc:
cycle(path)
else:
playsound(path)
if __name__ == "__main__":
# target呼叫play函式,args需要賦值元組
music=threading.Thread(target=play,args=(path,))
music.run() # 開始回圈
這樣音樂就會在新建的子執行緒中運行,不會干擾到主執行緒,
另外,下面這個殺死執行緒的方法,可以幫助你更主動的停止音樂(網上找的)
import threading
import inspect
import ctypes
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
if __name__ == "__main__":
music=threading.Thread(target=play,args=(path,))
music.run() # 開始回圈
stop_thread(music) # 殺死執行緒
可以借此做一個簡單的音樂播放器
但是playsound的播放無法中斷,stop_thread()只能在單次音樂播放完成后才停止,如果沒有解決辦法的話,復雜功能恐怕做不了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/195286.html
標籤:其他
