错误:__ init __()缺少1个必需的位置参数:'rec'

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了错误:__ init __()缺少1个必需的位置参数:'rec'相关的知识,希望对你有一定的参考价值。

我是python的新手。我正在尝试制作应该检测,收听,记录和写入.wav文件的麦克风文件。但是,它在尝试运行文件时给我一个错误。就是说:

TypeError: __init__() missing 1 required positional argument: 'rec'

而且我对listen()的问题如下。这是我的代码:

class Recorder:
# compute the rms
def rms(frame):
    count = len(frame) / swidth
    format = "%dh" % (count)
    shorts = struct.unpack(format, frame)

    sum_squares = 0.0
    for sample in shorts:
        n = sample * SHORT_NORMALIZE
        sum_squares += n * n
    rms = math.pow(sum_squares / count, 0.5);
    return rms * 1000

# create an interface to portaudio
@staticmethod
def __init__(rec):
    rec.p= pyaudio.PyAudio()
    rec.stream= rec.p.open(format=FORMAT, channels=CHANNELS, rate=RATE,input=True,output=True,frames_per_buffer=chunk)

# record the detected sound
def record(rec):
    print('sound detected, record begin')
    frames = []
    current = time.time()
    end = current + Timeout
    while current <= end:
        data = rec.stream.read(chunk, execption_on_overflow=False)
        if rec.rms(data) >= Threshold:
            end = time.time() + Timeout
        current = time.time()
        frames.append(data)
    rec.write(b''.join(frames))

# write the recorded sound to .wav file
def write(rec, recording):
    files = len(os.listdir(FileNameTmp))
    filename = os.path.join(FileNameTmp,time.strftime('%Y_%m_%d-%H_%H_%M_%S.wav'.format(FORMAT)))
    filename2 = time.strftime('%Y_%m_%d-%H_%H_%M_%S.wav'.format(FORMAT))
    wf = wave.open(filename, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(rec.p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(recording)
    wf.close()
    print('Written to file: '.format(filename))
    print('Returning to listening')

# listen to the sound
def listen(rec):
    print('Listening beginning')
    while True:
        input = rec.stream.read(chunk, execption_on_overflow=False)
        rms_val = rec.rms(input)
        if rms_val > Threshold:
            rec.record()
k = Recorder()
k.listen()
答案

您将__init__声明为staticmethod,因此self(或者在您的情况下为rec)参数传递到了构造函数中。当您要使用静态构造函数时,请查看this

以上是关于错误:__ init __()缺少1个必需的位置参数:'rec'的主要内容,如果未能解决你的问题,请参考以下文章

如何修复modelformset错误:__init __()缺少1个必需的位置参数:'user'

错误:__ init __()缺少1个必需的位置参数:'rec'

类型错误:__init__() 缺少 2 个必需的位置参数:“arr”和“n”

__init__() 缺少 1 个必需的位置参数:'self' [关闭]

Spyder 未以 TypeError 开头:__init__() 缺少 1 个必需的位置参数

类型错误:initialize() 缺少 1 个必需的位置参数:'url'