我正在尝试在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}
你可以指导我解决这个问题吗?
答案 0 :(得分:2)
通过改变参数值,阅读不同的用户体验和纠正后。
作为专家描述,
的实际原因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()
答案 1 :(得分:0)
我遇到了同样的问题,并试图改变块大小和采样率而没有成功。通过使用多处理,问题得到了解决。这是我的代码:
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/"
答案 2 :(得分:0)
我在交互式环境(Jupyter Notebook)中运行时遇到了同样的问题,对我来说,它最终是由于在代码运行之间没有清除缓冲区造成的。请注意,根据 RATE、CHUNK、RECORD_SECONDS 的值,for 循环有可能使块未读。运行此代码段以查看:
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)并记录整数秒长,以便缓冲区中没有任何数据。