我是python的新手。我试图调用一个类的构造函数,但它给了我以下错误:
TypeError: init ()缺少1个必需的位置参数:“ rec”
而且我对listen()有如下相同的问题。请丢弃rms()
和record()
,因为它们是其他函数,这是我的代码:
class Recorder:
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)
# 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()
答案 0 :(得分:2)
mmh我无法重现该错误。我只关注__init__
方法,因为那是您的关键部分。
Test.py
import pyaudio
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
class Recorder:
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)
# listen to the sound
def listen(rec):
print('Listening beginning')
if(__name__ == "__main__"):
k = Recorder()
k.listen()
>> python Test.py
>> Listening beginning
还有我的设置
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyaudio
>>> print(pyaudio.__version__)
0.2.11
因此,请指定您的版本并提供有关您的问题的其他信息。
我假设您使用类似
的构造函数def __init__(self, rec):
...
但是您不会将任何参数传递给rec
。这可以解释您的错误:
Traceback (most recent call last):
File ".../Test.py", line 20, in <module>
k = Recorder()
TypeError: __init__() missing 1 required positional argument: 'rec'
答案 1 :(得分:-1)
我认为问题出在其他方法上,您的代码无法全部显示... Record还有其他方法,例如“ record”和“ rms”。
def listen(rec):
print(“开始听”)
为True时
input = rec.stream.read(chunk,execption_on_overflow = False)
rms_val = rec.rms(输入)#现在,如果您的错误出现在这里,我该怎么办?
如果rms_val>阈值:
rec.record()#还是在这里?
如果您在此方法中调用 init ()函数,我现在就不能...