When we are using numpy.frombuffer() to convert a bytes to numpy array, we may get this error: ValueError: buffer size must be a multiple of element size. In this tutorial, we will introduce you how to fix this error.
Look at this example:
import librosa wav_file = "music-jamendo-0039.wav" wav_data, sr = librosa.load(wav_file, mono=True) print(wav_data) print(wav_data.dtype) import numpy as np print(wav_data[0:50]) b = wav_data.tobytes() x = np.frombuffer(b, dtype = np.float) print(type(x)) print(x[0:50])
Here we use np.float to convert a bytes to numpy array.
x = np.frombuffer(b, dtype = np.float)
Run this code, we will see: ValueError: buffer size must be a multiple of element size
How to fix this error?
We should set dtype in numpy.frombuffer() correctly.
For example:
If dtype = np.int16
x = np.frombuffer(b, dtype = np.int16)
We will find x is:
[-24422 13481 -24658 13714 -8626 -18935 -17005 13767 -23484 13714 12668 -18760 19671 14155 -22622 14337 -14007 14086 30525 -18655 -1029 14063 31102 13097 -3852 -18456 12771 -18522 26295 13852 -8508 13838 -27266 -18925 -4946 13532 3331 13702 -4075 -19116 -25870 -19160 28735 13790 5765 -19113 24229 -18936 25993 13996]
The value of x is not the same to wav_data.
In order to get the right value of x, we should set dtype = np.float32, which is the dtype of wav_data.
Here x is:
[ 3.1595556e-07 1.0924321e-06 -2.0543989e-06 1.4881829e-06 1.0925655e-06 -5.4893881e-06 1.2117634e-05 3.0912117e-05 8.0338878e-06 -9.6241101e-06 7.1520894e-06 3.9458875e-08 -2.7768758e-05 -1.9811972e-05 2.3305599e-06 2.1289316e-06 -2.1991723e-06 4.1150400e-07 9.9875649e-07 -7.9325520e-07 -6.2810352e-07 1.6572957e-06 -8.0126512e-07 -2.0320670e-06 5.1378197e-06 -5.1078187e-06 -2.8517738e-05 -1.7178845e-05 7.3522529e-06 -6.6071664e-07 -4.5573697e-06 8.0500204e-06 -8.8221705e-06 -3.0072155e-05 -1.2288952e-05 5.9455974e-06 -6.2966063e-07 -2.5200138e-06 2.6032403e-06 -4.4498762e-07 -1.7536241e-06 1.9865117e-06 -3.9684135e-08 -2.2182173e-06 2.2615259e-06 8.9228968e-07 -5.3025328e-06 6.0253165e-06 2.5768280e-05 1.8642553e-05]
The value of x is same to wav_data.
Finally, this error is fixed.