我遇到了一个非常奇怪的问题,我设法尽可能减少这个问题:
import sounddevice
import time
class SamplerBox:
def __init__(self):
self.samples = {}
def audio_callback(self, outdata, frame_count, time_info, status):
print('ac')
def init(self):
self.connect_audio_output()
self.load_samples()
time.sleep(20)
def connect_audio_output(self):
try:
sd = sounddevice.OutputStream(callback=self.audio_callback)
sd.start()
print('Opened audio device')
except:
print('Invalid audio device')
exit(1)
def load_samples(self):
for midinote in range(128):
for velocity in range(128):
self.samples[midinote, velocity] = Sound()
class Sound:
def __init__(self):
pass
sb = SamplerBox()
sb.init()
一旦我创建了那个大的
self.samples
字典,并且仅创建带有空回调的新音频流,我就会在 Python 3.11 中收到“总线错误 10”。
使用 Python 3.9 我得到“非法指令 4”
在我的原始脚本(此处简化)中,我得到了“Segmentation Failure 11”
我在 MacOS 10.15.7 上运行 Homebrew Python 3.11。
最糟糕的是,以程序方式编写,它运行完美:
import sounddevice
import time
samples = {}
class Sound:
def __init__(self):
pass
def audio_callback(self, outdata, frame_count, time_info, status):
print('ac')
try:
sd = sounddevice.OutputStream(callback=audio_callback)
sd.start()
print('Opened audio device')
except:
print('Invalid audio device')
exit(1)
for midinote in range(128):
for velocity in range(128):
samples[midinote, velocity] = Sound()
time.sleep(20)
有什么想法吗?
您没有保留对在
connect_audio_output
中创建的输出流对象的引用,因此当该方法完成时,与 局部变量
sounddevice.OutputStream
关联的 sd
对象将丢失其所有引用,并最终由 GC 收集.
保持对象存活,例如通过将其分配给实例属性:
def connect_audio_output(self):
try:
self.sd = sounddevice.OutputStream(callback=self.audio_callback)
self.sd.start()
print('Opened audio device')
except:
print('Invalid audio device')
exit(1)