python音频播放——利用playsound和Thread库在子线程播放

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()只能在单次音乐播放完成后才停止。如果没有解决办法的话,复杂功能恐怕做不了。

猜你喜欢

转载自blog.csdn.net/weixin_46251846/article/details/109297348
今日推荐