python - 使用 QThread 在文件中写入录音时崩溃
问题描述
我是多线程开发的新手,我正在尝试做一个“简单”的应用程序,从几个 tutos 中启发自己。2个线程并行运行:
- 线程1:录制来自麦克风的声音并保存在文件中
- 线程 2:进度条(到目前为止,恒定值为 5 秒)
在不保存文件的情况下,我设法使两个线程并行运行,但是当我使用从 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())
我想我在对线程管理的理解中一定遗漏了一些东西,但我不明白。任何帮助将不胜感激,谢谢!
解决方案
推荐阅读
- hadoop - 在不引发异常的情况下测试 Kerberos 身份验证
- python - Beautiful Soup 找不到标签
- amazon-web-services - 如果所有架构组件都是特定于 aws 的产品,那么选择 Terraform 而不是 AWS CloudFormation 的正当理由是什么?
- visual-studio - 将 azure 广告组添加到 Visual Studio 中的表格模型
- logic - 合金建模语言——如何编写过滤器?
- search-engine - Google 的 pageRank 中的“随机跳转”到底是什么意思?
- google-ads-api - 广告的默认类型?
- node.js - node.js如何从中间件内部的redis数据库中获取数据
- java - 为多个配置文件设置弹簧配置
- java - 在不同布局中的另一个图像视图上设置一个图像视图