0

I am working with speech recognition library in Python and trying to save an audio file after submiting to the API that recognize it. So, my problem comes when I want to save that audio to a file.

import speech_recognition as sr

r = sr.Recognizer()
mic = sr.Microphone()

print('Recording...')
with mic as source:
    audio = r.listen(source)

with open("audio_file.wav", "wb") as file:
    file.write(audio.frame_data)

The audio_file.wav have a size approximately of 210kb(about 4 or 5 seconds recording)

when I try to reproduce the audio file.wav, the player throws an error saying that can not play the audio... due to a codec problem.

My question are: am I missing save a headers or something like that? Is there another way to saves audio bytes into a file?

Edit My answer is in this question Wav file from microphone on Python

arielbi.289
  • 11
  • 1
  • 5
  • assuming `audio.frame_data` is a byte-like structure, this code should work, although a safer and more idiomatic way is to use context manager: `with open("audio_file.wav", "wb") as file: file.write(audio.frame_data)`, since it will make sure that the file is closed even if something happens during the `write` operation. Additionally you may add `file.flush()` after `write` to make sure that the output is flushed to disk. – Taras Tsugrii Jan 23 '19 at 18:25
  • @TarasTsugrii. The audio.frame_data is a `````` type. I check with the safe mode that you suggest and keep getting the same result. Thanks any way. – arielbi.289 Jan 23 '19 at 18:52
  • You still didn't explain what the problem is, it should create a file just fine. – Nikolay Shmyrev Jan 23 '19 at 20:21
  • @NikolayShmyrev I edited the question to make it more simple. I hope that in this way it is easier to understand. – arielbi.289 Jan 23 '19 at 21:00
  • You can open this headerless file in audacity. – Nikolay Shmyrev Jan 23 '19 at 22:36
  • In case you need to save it with a header you can use wave module. – Nikolay Shmyrev Jan 23 '19 at 22:42
  • Possible duplicate of [Binary string to wav file](https://stackoverflow.com/questions/33245371/binary-string-to-wav-file) – Nikolay Shmyrev Jan 23 '19 at 22:42
  • I just find the answer in another question [Wav file from microphone on Python](https://stackoverflow.com/questions/46738569/wav-file-from-microphone-on-python) – arielbi.289 Jan 24 '19 at 16:15

1 Answers1

4

Change audio.frame_data to audio.get_wav_data().

brasofilo
  • 25,496
  • 15
  • 91
  • 179