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.
JavaScript
x
20
20
1
def read_wave(self, path: str) -> Dict:
2
with contextlib.closing(wave.open(path, "rb")) as wf:
3
4
num_channels: int = wf.getnchannels()
5
assert num_channels == 1
6
sample_width: int = wf.getsampwidth()
7
assert sample_width == 2
8
sample_rate: int = wf.getframerate()
9
assert sample_rate in (8000, 16000, 32000)
10
frames: int = wf.getnframes()
11
pcm_data: bytes = wf.readframes(frames)
12
duration: float = frames / sample_rate
13
14
return {
15
"pcm_data": pcm_data,
16
"sample_rate": sample_rate,
17
"duration": duration,
18
}
19
20
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.
JavaScript
1
5
1
@app.post(path="/upload-audios/")
2
async def upload_audios(audios: list[UploadFile] = File( )):
3
pass
4
5
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).