我想知道是否有一种方法可以停止记录并导出Python中finally:语句中的记录。示例:假设我正在录制,然后我的脚本在录制时突然崩溃,是否有办法停止录制和导出这种情况?
我尝试制作一个单独的函数来导出并停止记录并最终运行:,但这不起作用,它只是创建了一个新文件。任何帮助将不胜感激。我的代码如下:
import pyaudio
import wave
import time
import signal
from datetime import datetime
# Configuration
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 10
# Initialize PyAudio
audio = pyaudio.PyAudio()
def record_audio(filename):
stream = audio.open(format=FORMAT, channels=CHANNELS,
rate=RATE, input=True, frames_per_buffer=CHUNK)
print("Recording started")
frames = []
data = stream.read(CHUNK)
frames.append(data)
print("Recording stopped")
stream.stop_stream()
stream.close()
# Save to WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
def main():
try:
while True:
timestamp = datetime.now().strftime("%m-%d-%Y_%H-%M-%S")
wav_filename = f"/home/henrikkoehler/Desktop/Audio_Files/{timestamp}.wav"
record_audio(wav_filename)
print(f"Audio saved to {wav_filename}")
# Wait a bit to avoid multiple recordings from a single press
time.sleep(1)
except KeyboardInterrupt:
print("Exiting...")
except:
time.sleep(1)
t_end = time.time() + 15 * 1
while time.time() < t_end:
print("Error! Restart!")
finally:
audio.terminate()
if __name__ == "__main__":
main()
要回答您的问题,只需将您的文件写入(
#Save to WAV file
代码)移动到您的finally
语句中,然后您的audio.terminate()
应该可以工作。
finally:
try: #attempt to close stream/recording in case it has not been closed
stream.stop_stream()
stream.close()
except: pass #if already closed and an error is given, don't do anything
# Save to WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
audio.terminate()
但是……
首先,在
while True
函数中使用 main()
将会一个接一个地重复创建录音,即使您已经录制了一个录音。除非这是您想要做的,否则您应该删除 while
循环并将代码从 record_audio()
函数移回到 main()
函数中。其次,你的代码只是记录/读取一个单独的块,然后完成记录。 要记录一定的持续时间,请使用 for 循环:
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)