I have some code that generates audio, and sometimes raises due to different reasons. I want to write the audio generated straight into a wav file. However, due to being inside the wave
s context via with
, wave
tried to close the file. Now that is fine if it's later in the process, but if it's at the very beginning, wave
doesn't have any params set, and dies.
Here's a MWE:
from io import BytesIO
import wave
audio_out = BytesIO()
with wave.open(audio_out, "w") as file_out:
raise Exception('aaa!')
Error: # channels not specified
The best I could come up with was to include file_out.setparams((1, 1, 1, 1, 'NONE', ''))
at the very top, before anything gets a change to raise, and then overwrite those with the real params once I have them. It feels a bit dirty, though. Is there a better solution? Thanks!
IDEA: Removing the context manager
I tried removing the context manager:
file_out = wave.open(audio_out, "w")
raise Exception('aaa!')
but wave
closes the file unconditionally still. The docs actually mention this: Wave_write.close(): Make sure nframes is correct, and close the file if it was opened by wave. This method is called upon object collection. [...]
So what happens in this case is that I get a printout saying Exception ignored in: <bound method Wave_write.__del__ of <wave.Wave_write object at 0x7ff549064eb8>> [...] wave.Error: # channels not specified
, which is still not satisfactory.