lse23
lse23

Reputation: 1711

ValueError: buffer size must be a multiple of element size

I am a newbie to python and I am trying to denoise a audio file using an API. Below is the code I am using and on execution it gives me the error "ValueError: buffer size must be a multiple of element size". Anyone can help me out in solving the issue please?

import requests
import scipy.io.wavfile
import numpy as np

file_name = 'audio.mp3'
files = {'file': open(file_name, 'rb')}

denoise_level = 20
querystring = {"denoise_control": denoise_level}

headers = {
    'x-api-key': "my-api-key"
}

url = "https://noise-reduction-service.p.rapidapi.com/denoise"

response = requests.request("POST", url, files=files, headers=headers, params=querystring)

content = np.frombuffer(response.content, dtype=np.int32)

sample_rate = 44100
scipy.io.wavfile.write('denoised_speech.wav', sample_rate, content)

Thanks in advance!

Upvotes: 4

Views: 8948

Answers (1)

sauerburger
sauerburger

Reputation: 5148

This happens when np.frombuffer() tries to take the response form the API and interpret is as a sequence of 4-byte integers (32bit). In that case, the response needs to be a multiple of 4-bytes. If this is not the case, numpy raises the exception. (For example, what should it do if there are 3 bytes left at the end of the stream?)

Without more information about API, its difficult to investigate this. Have you checked the response? I can think of three possible issues:

  • The response might be an error message. Also check response.status_code.
  • Does the response only consist of the binary stream? The processed data might be embedded in a json document.
  • Is the returned audio really encoded as raw 4-byte integers? It could be encoded as 2-byte integers. (Or it could be an mp3. In that case save the response to a file without using scipy.io.wavfile.write()).

Upvotes: 3

Related Questions