我正在尝试一次录制多个(〜12)小时的麦克风。尝试关闭流时出现结构错误,但仅在长时间记录后才会发生。
这是我的代码:
import pyaudio
import wave
import sys
import keyboard
if __name__ == '__main__':
print('recording')
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "raw_radio.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
frames = []
flag = False
try:
while(not flag and sys.getsizeof(frames) < sys.maxsize * .8):
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
try:
data = stream.read(CHUNK)
frames.append(data)
except Exception as e:
print(e)
flag=True
except KeyboardInterrupt:
print('ended recording, now saving')
pass
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()
这是标准输出:
recording
ended recording, now saving
Traceback (most recent call last):
File ".\record_mic.py", line 54, in <module>
wf.writeframes(b''.join(frames))
File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\wave.py", line 427, in writeframes
self.writeframesraw(data)
File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\wave.py", line 416, in writeframesraw
self._ensure_header_written(len(data))
File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\wave.py", line 457, in _ensure_header_written
self._write_header(datasize)
File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\wave.py", line 474, in _write_header
self._sampwidth * 8, b'data'))
struct.error: argument out of range
Exception ignored in: <bound method Wave_write.__del__ of <wave.Wave_write object at 0x000001CA028A5FD0>>
Traceback (most recent call last):
File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\wave.py", line 316, in __del__
File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\wave.py", line 434, in close
File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\wave.py", line 457, in _ensure_header_written
File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\wave.py", line 474, in _write_header
struct.error: argument out of range
我在想,因为我必须两次按Ctrl + C才能引发KeyboardInput错误,我正在做一些错误地编辑框架列表的事情。
您正在尝试编写比wave格式可以表示的波形文件长的波形文件。您正尝试一次写入2 * 44100 * 2 *(12 * 3600)或7.3GB。
失败的代码是
self._file.write(struct.pack('<L4s4sLHHLLHH4s',
36 + self._datalength, b'WAVE', b'fmt ', 16,
WAVE_FORMAT_PCM, self._nchannels, self._framerate,
self._nchannels * self._framerate * self._sampwidth,
self._nchannels * self._sampwidth,
self._sampwidth * 8, b'data'))
这将写入wave标头。第一个L是数据的长度加上标题,该标题将数据限制为4294967259字节。这是4GB-36个字节
将文件分块写入。