python音訊播放——利用playsound和Thread庫在子執行緒播放

2020-10-28 14:00:33

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()只能在單次音樂播放完成後才停止。如果沒有解決辦法的話,複雜功能恐怕做不了。