【问题标题】:IOError: [Errno Input overflowed] -9981IOError: [Errno 输入溢出] -9981
【发布时间】:2015-03-26 07:22:42
【问题描述】:

我试图在我的 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}

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

【问题讨论】:

  • 通常,输入溢出意味着数据到达的速度快于计算机读取数据的能力。你能知道你是否收到了任何数据吗?
  • @HeatfanJohn 在命令终端上它正在接收来自此命令的音频输入arecord -D plug:default -f S16_LE -c 1 -r 16000 -d 300 a.wav
  • @HeatfanJohn 我如何在 python 上知道它是否真的在接收数据,尽管它显示了上述错误
  • 可能在 python 脚本中的data = stream 行之前添加一个print i
  • @HeatfanJohn 当我在 python 脚本 * recording 0 1 Traceback (most recent call last): File "/home/pi/pythonsound/myaudio01JAN27.py", line 25, in &lt;module&gt; 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 中的 data=stream 之前添加 print i 行时,我得到了这个输出

标签: python audio raspbian ioerror


【解决方案1】:

在阅读了不同的用户体验和他们的修正后,只需改变参数的值。

正如上面一位专家所描述的,真正的原因

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()

【讨论】:

    【解决方案2】:

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

    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/"
    

    【讨论】:

      【解决方案3】:

      我在交互式环境(Jupyter Notebook)中运行时遇到了同样的问题,对我来说,这最终是由于在代码运行之间没有清除缓冲区造成的。请注意,根据 RATE、CHUNK、RECORD_SECONDS 的值,for 循环可能会留下未读取的块。运行这个 sn -p 看看:

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

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

      【讨论】:

        猜你喜欢
        • 2013-01-17
        • 2012-01-23
        • 2016-02-23
        • 2023-03-15
        • 1970-01-01
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多