We often use base64 to encode an audio file to transfer. In this tutorial, we will introduce you how to save it to a wav file.
Base64 encode and decode
In order to understand how to use base64, you can read:
Improve Python Base64 to Encode String Safely: Replace +, / and = Characters- Python Tutorial
Python Implements Images Base64 Encode for Beginners – Python Tutorial
In order to save a Codec = pcm and encoded by python base64, we should decode it first.
Here is an example:
audio = base64.b64decode(audio)
How to save audio byte data to wav?
Here is an example:
import wave audio = base64.b64decode(audio) with wave.open(wave_file, 'wb') as wav: wav.setparams((1, 2, 16000, 0, 'NONE', 'NONE')) wav.writeframes(audio)
This example will save pcm data to a wave file with sample rate = 16000.
As to wav.setparams(), it is defined as:
Wave_write.setparams((nchannels, sampwidth, framerate, nframes, comptype, compname))
From this example above,we can find:
1.nchannels = 1, which means we will save audio data with channel = 1
2.The sampwidth = 2, which means we will save audio data with 16 bits
3.framerate = 16000, which means the sample rate of wave file is 16k