我有一个函数在单独的线程中循环播放声音文件(取自this question的答案),我的函数作为参数获取它应该播放的文件的名称。
def loop_play(sound_file):
audio = AudioSegment.from_file(sound_file)
while is_playing:
play(audio)
def play_sound(sound_file):
global is_playing
global sound_thread
if not is_playing:
is_playing = True
sound_thread = Thread(target=loop_play,args=[sound_file])
sound_thread.daemon = True
sound_thread.start()
每次拨打play_sound
时,我都会覆盖sound_thread
并创建一个新线程。旧的会发生什么?它还在后台运行吗?有没有办法终止它?
答案 0 :(得分:3)
1)覆盖时:
旧的会怎么样?它还在后台运行吗?
您只覆盖了对该线程的引用,该线程本身仍在运行。
有没有办法终止它?
没有干净的终止线程的方法,请参阅:Is there any way to kill a Thread in Python?
2)如果你想停止线程,你应该使用全局变量来告诉线程停止。
stop = False
def loop_play(sound_file):
global stop
audio = AudioSegment.from_file(sound_file)
while is_playing:
if stop:
return
play(audio)
def play_sound(sound_file):
global is_playing
global sound_thread
global stop
if not is_playing:
stop = True
while sound_thread.isAlive(): # Wait for thread to exit
sleep(1)
stop = False
is_playing = True
sound_thread = Thread(target=loop_play,args=[sound_file])
sound_thread.daemon = True
sound_thread.start()
注意,我还没有完全理解你的代码中is_playing的含义。