首页 > 解决方案 > 使用 QThread 在文件中写入录音时崩溃

问题描述

我是多线程开发的新手,我正在尝试做一个“简单”的应用程序,从几个 tutos 中启发自己。2个线程并行运行:

在不保存文件的情况下,我设法使两个线程并行运行,但是当我使用从 scipy 导入的“写入”方法保存该文件时,我崩溃了。

import sys
import time

import sounddevice as sd
from scipy.io.wavfile import write
from playsound import playsound

class ThreadStatusBar(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)

    def run(self):
        cnt = 0
        while cnt < 100:
            cnt += 1
            time.sleep(0.05)
            self.change_value.emit(cnt)

class ThreadRecorder(QThread):

    def run(self):
        # Press the green button in the gutter to run the script.
        # Sampling frequency
        freq = 44100

        # Recording duration
        duration = 5

        # Start recorder with the given values of
        # duration and sample frequency

        print("start recording")
        recording = sd.rec(int(duration * freq), samplerate=freq, channels=2)

        # time.sleep(3)

        # Record audio for the given number of seconds
        sd.wait()
        # self.status("end recording")
        print("end recording")

        # This will convert the NumPy array to an audio
        # file with the given sampling frequency
        write("recording0.wav", freq, recording)

class Window(QDialog):
    def __init__(self):
        super().__init__()
        ...
        vbox.addWidget(self.progressbar)
        self.button1 = QPushButton("Record")
        self.button1.move(64, 32)
        self.button1.clicked.connect(self.startrecord)
        self.button1.setStyleSheet('background-color:grey')
        vbox.addWidget(self.button1)

        self.button2 = QPushButton("Play")
        self.button2.move(64, 132)
        self.button2.clicked.connect(self.play)
        self.button2.setStyleSheet('background-color:grey')

        vbox.addWidget(self.button2)
        self.setLayout(vbox)
        self.show()

    def play(self, name):
        print("play sound")
        playsound("recording0.wav")
        print("end")

    def startrecord(self):
        self.thread1 = ThreadStatusBar()
        self.thread1.change_value.connect(self.setProgressVal)
        self.thread2 = ThreadRecorder()

        self.thread1.start()
        self.thread2.start()

    def setProgressVal(self, val):
        self.progressbar.setValue(val)

App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())

我想我在对线程管理的理解中一定遗漏了一些东西,但我不明白。任何帮助将不胜感激,谢谢!

标签: pythonmultithreadingaudioaudio-recordingqthread

解决方案


推荐阅读