I have a function that receives a .wav audio path directory and return its pcm_data in bytes, sample_rate as int and duration as float.
def read_wave(self, path: str) -> Dict: with contextlib.closing(wave.open(path, "rb")) as wf: num_channels: int = wf.getnchannels() assert num_channels == 1 sample_width: int = wf.getsampwidth() assert sample_width == 2 sample_rate: int = wf.getframerate() assert sample_rate in (8000, 16000, 32000) frames: int = wf.getnframes() pcm_data: bytes = wf.readframes(frames) duration: float = frames / sample_rate return { "pcm_data": pcm_data, "sample_rate": sample_rate, "duration": duration, }
Now I want that the audio file comes from a uploaded audio using POST request with FastAPI, so if I upload a .wav audio using the UploadFile class from fastapi, I get a tempfile.SpooledTemporaryFile, how can I adapt the first function for this case.
@app.post(path="/upload-audios/") async def upload_audios(audios: list[UploadFile] = File(...)): pass
Advertisement
Answer
The wave.open
function supports a file like object, so you can use the .file
attribute of UploadFile
directly (it represents the SpooledTemporaryFile instance).