Last active
January 23, 2025 00:33
-
-
Save hadware/8882b980907901426266cb07bfbfcd20 to your computer and use it in GitHub Desktop.
Convert wav in bytes for to numpy ndarray, then back to bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from scipy.io.wavfile import read, write | |
import io | |
## This may look a bit intricate/useless, considering the fact that scipy's read() and write() function already return a | |
## numpy ndarray, but the BytesIO "hack" may be useful in case you get the wav not through a file, but trough some websocket or | |
## HTTP Post request. This should obviously work with any other sound format, as long as you have the proper decoding function | |
with open("input_wav.wav", "rb") as wavfile: | |
input_wav = wavfile.read() | |
# here, input_wav is a bytes object representing the wav object | |
rate, data = read(io.BytesIO(input_wav)) | |
# data is a numpy ND array representing the audio data. Let's do some stuff with it | |
reversed_data = data[::-1] #reversing it | |
#then, let's save it to a BytesIO object, which is a buffer for bytes object | |
bytes_wav = bytes() | |
byte_io = io.BytesIO(bytes_wav) | |
write(byte_io, rate, reversed_data) | |
output_wav = byte_io.read() # and back to bytes, tadaaa | |
# output_wav can be written to a file, of sent over the network as a binary |
This is awesome, thanks!
I needed to create a pipeline like this:
python -> ffmpeg -> ffmpeg -> python
Your method helped with both sides of this.
Thanks io.BytesIO(input_wav) saved my life
I owe you a beer.
Thank you, that really helped me!
ValueError: File format b'\xff\xf3d\xc4' not understood. Only 'RIFF' and 'RIFX' supported.
Your wav file must be malformed (or not a wav at all). Inspect it using ffprobe for instance.
Your wav file must be malformed (or not a wav at all). Inspect it using ffprobe for instance.
Thanks, you are right, it's actually a "mp3" file, sorry for the inconvience.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this HIDDEN INFORMATION. Thanks....