我正在编写一个 Python 应用程序来将音频录制为 WAV 文件,直到用户按下pause或stop。暂停音频后,用户还应该能够恢复录制。此外:
- 该应用程序无法预先知道录音会持续多长时间
- 该应用程序应避免内存不足(因为录音可能很长)。例如,它可以实时写入 WAV 文件,以防止将不断增长的录音存储在内存中。
解决这个问题的好方法是什么?您能否为您的解决方案提供一些代码片段?
使用python-sounddevice,我可以stop()
和start()
流来模仿“暂停”功能。我可以指定一个 numpy 数组作为记录的输出。但:
- 我不知道阵列有多大(因为我不知道记录时长)
- 当数组填满时我会怎么做?
python-sounddevice 和 sound-file可以在不知道大小的情况下支持录音。但:
- 我将如何结合“暂停”和“恢复”功能?声音文件只有
read
和write
方法。 - 有没有比使用 a 更好的方法来停止流
KeyBoardInterrupt
? - 我可以在每次“暂停”后创建不同的录音并在用户单击“停止”后合并 WAV 文件吗?
- 我尝试使用
Threading.Event()
阻止录制线程来模仿暂停功能,但录制一直在写入文件
sound-device
我的尝试
paused = False
def record():
self.recording = ? # create numpy.ndarray of the correct size
# (not sure the best way to do this without
# knowing the recording duration)
with sd.InputStream(samplerate=44100, device=mic, channels=1,
callback=self.callback):
while self.paused:
sd.stop()
sd.rec(out=recording) # but what happens if
# recording is very long
# or numpy array fills up?
def stop_and_save():
sd.stop()
scipy.io.wavfile.write("recording.wav", 44100, self.recording)
和sound-device
方法sound-file
:
with sf.SoundFile(args.filename, mode='x', samplerate=args.samplerate,
channels=args.channels, subtype=args.subtype) as file:
with sd.InputStream(samplerate=args.samplerate, device=args.device,
channels=args.channels, callback=callback):
print('press Ctrl+C to stop the recording')
while True:
file.write(q.get()) # but how do you stop writing when 'paused'?
except KeyboardInterrupt:
print('\nRecording finished: ' + repr(args.filename))
parser.exit(0)
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))