0

我需要为我用 python 和 PyQt5 编写的 voip 应用程序线程化。该线程执行播放铃声工作。但我不知道如何阻止这个线程播放,我需要一种像terminate进程中这样的方法来干净、简单地杀死线程,但我找不到。我不得不提到我不能使用 Process 和 multiProcessing (有一个问题是我找不到以最小的方式显示它的方法)。

这是我的问题的最小化代码:

import playsound
# from multiprocessing import Process
from playsound import playsound
from threading import Thread


class Test:
    def __init__(self):
        self.ringTone = True
    def ringTonePlay(self):
        while self.ringTone:
            playsound("ring_tone.wav")

    def testFunction(self):
        self.p1 = Thread(target = self.ringTonePlay)
        self.p1.start()

    def stopFunction(self):
        self.ringTone = False


test = Test()
test.testFunction()
test.stopFunction()

当我调用stopFunction函数时,它仍然在响。您建议以什么方式终止播放线程?

4

1 回答 1

0

您可以使用threading.Event。您可以根据需要阻止和取消阻止线程。

编辑:如果playsound在不同的线程中播放给定的声音,您可能需要查看有关如何停止/阻止它的文档。

例子:

import playsound
import threading
from playsound import playsound

class Ringtone(threading.Thread):
    def __init__(self, threadID, name):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.event = threading.Event()
    def run(self):
        while True:
            self.event.wait()
            playsound("ring_tone.wav")

ringtone = Ringtone(1, "Ringtone")
ringtone.start()

# To block the thread
ringtone.event.clear()

# To unblock the thread
ringtone.event.set()
于 2019-07-25T13:37:46.520 回答