IOError: [Errno Input overflowed] -9981

IOError: [Errno Input overflowed] -9981

我正在尝试在我的 RaspberryPi 型号 B 板上的 Rasbian 上执行 PyAudio python 捕获程序,但出现错误:

Traceback (most recent call last):
  File "/home/pi/pythonsound/record.py", line 35, in <module>
    data = stream.read(CHUNK)
  File "/usr/local/lib/python2.7/dist-packages/pyaudio.py", line 605, in read
    return pa.read_stream(self._stream, num_frames)
IOError: [Errno Input overflowed] -9981

还有一些其他建议可用但无效 这是我试过的, 这是代码

import pyaudio
import wave
import sys
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5

WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

这是我的 USB 声卡设备信息,

{'defaultSampleRate': 44100.0, 
'defaultLowOutputLatency': 0.011609977324263039, 
'defaultLowInputLatency': 0.011609977324263039, 
'maxInputChannels': 1L, 
'structVersion': 2L, 
'hostApi': 0L, 
'index': 0, 
'defaultHighOutputLatency': 0.046439909297052155, 
'maxOutputChannels': 2L, 
'name': u
'USB PnP Sound Device: USB Audio (hw:0,0)', 
'defaultHighInputLatency': 0.046439909297052155}

你能指导我解决这个问题吗?

在阅读了不同的用户体验和他们对仅更改参数值的修正后。

如专家所述,

的真正原因
IOError: [Errno Input overflowed] -9981

所以我也开始增加 CHUNK 的值,最后我也成功解决了这个错误。 现在我修正后的编码是:

import pyaudio, wave, time, sys
from datetime import datetime

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5

current_time = str(datetime.now())  #"Date/Time for File Name"
current_time = "_".join(current_time.split()).replace(":","-")
current_time = current_time[:-7]
WAVE_OUTPUT_FILENAME = 'Audio_'+current_time+'.wav'

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT, channels = CHANNELS, rate = RATE, input = True, input_device_index = 0, frames_per_buffer = CHUNK)

print("* recording")

frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    print i
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

我遇到了同样的问题并尝试更改块大小和采样率但没有成功。通过使用多处理,问题得到解决。这是我的代码:

recordAudioSamples.py

import pyaudio
import wave
import datetime
import signal
import ftplib
import sys
import os

# configuration for assos_listen
import config


# run the audio capture and send sound sample processes
# in parallel
from multiprocessing import Process

# CONFIG
CHUNK = config.chunkSize
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = config.samplingRate
RECORD_SECONDS = config.sampleLength

# HELPER FUNCTIONS

# write to ftp
def uploadFile(filename):

    print("start uploading file: " + filename)
    # connect to container
    ftp = ftplib.FTP(config.ftp_server_ip, config.username, config.password)

    # write file
    ftp.storbinary('STOR '+filename, open(filename, 'rb'))
    # close connection
    ftp.quit()
    print("finished uploading: " +filename)


# write to sd-card
def storeFile(filename,frames):

    print("start writing file: " + filename)
    wf = wave.open(filename, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()
    print(filename + " written")


# abort the sampling process
def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')

    # close stream and pyAudio
    stream.stop_stream()
    stream.close()
    p.terminate()

    sys.exit(0)

# MAIN FUNCTION
def recordAudio(p, stream):

    sampleNumber = 0
    while (True):
        print("*  recording")
        sampleNumber = sampleNumber +1

        frames = []
        startDateTimeStr = datetime.datetime.now().strftime("%Y_%m_%d_%I_%M_%S_%f")
        for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
            data = stream.read(CHUNK)
            frames.append(data)

        fileName =  str(config.sensorID) + "_" + startDateTimeStr + ".wav"

        # create a store process to write the file in parallel
        storeProcess = Process(target=storeFile, args=(fileName,frames))
        storeProcess.start()

        if (config.upload == True):
            # since waiting for the upload to finish will take some time
            # and we do not want to have gaps in our sample
            # we start the upload process in parallel
            print("start uploading...")
            uploadProcess = Process(target=uploadFile, args=(fileName,))
            uploadProcess.start()



# ENTRYPOINT FROM CONSOLE
if __name__ == '__main__':

    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)


    # directory to write and read files from
    os.chdir(config.storagePath)

    # abort by pressing C
    signal.signal(signal.SIGINT, signal_handler)
    print('\n\n--------------------------\npress Ctrl+C to stop the recording')

    # start recording
    recordAudio(p, stream)

config.py

### configuration file for assos_listen
# upload
upload = False

# config for this sensor
sensorID = "al_01"

# sampling rate & chunk size
chunkSize = 8192
samplingRate = 44100 # 44100 needed for Aves sampling
# choices=[4000, 8000, 16000, 32000, 44100] :: default 16000

# sample length in seconds
sampleLength = 10

# configuration for assos_store container
ftp_server_ip = "192.168.0.157"
username = "sensor"
password = "sensor"

# storage on assos_listen device
storagePath = "/home/pi/assos_listen_pi/storage/"

我在交互式环境 (Jupyter Notebook) 中 运行 时遇到了同样的问题,对我来说,它最终是由代码运行之间未清除缓冲区引起的。请注意,for 循环有可能留下未读块,具体取决于 RATE、CHUNK、RECORD_SECONDS 的值。 运行这个片段看:

CHUNK = 1024
RATE = 44100
RECORD_SECONDS = 5
count = RATE * RECORD_SECONDS
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    count = count - CHUNK
    print("Buffer unread count:", count)`

这导致缓冲区中仍有 340 个样本。我认为这会导致下次执行代码时出现缓冲区溢出错误。我在 1.0 正下方和 1.0 正上方试验了 RATE/CHUNK 的多次运行和比率,我不清楚什么条件会触发超限错误。当我 运行 比 1 (48000/4799) 略小于 1 (48000/4799),然后在 3 秒采样时比 1 (48000/4801) 略大于 1 (48000/4801)。这似乎是运行将数据留在缓冲区中的累积效应,在某些时候会触发溢出条件。

为了解决这个问题,我最终使用了采样频率的偶数倍的 CHUNK(例如 4800 表示 48000kHz)并记录了整数秒长,这样缓冲区中就没有数据了。