简体   繁体   中英

How to get wave module methods for reading a .wav audio but with a temporary file tempfile.SpooledTemporaryFile obtained from fastAPI post request?

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

The wave.open function supports a file like object, so you can use the .file attribute of UploadFile directly (it represents the SpooledTemporaryFile instance).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM