简体   繁体   English

如何获得用于读取 a.wav 音频但使用从 fastAPI post 请求获得的临时文件 tempfile.SpooledTemporaryFile 的 wave 模块方法?

[英]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.我有一个 function,它接收 a.wav 音频路径目录并以字节为单位返回其 pcm_data,sample_rate 为 int,duration 为 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.现在我希望音频文件来自使用 FastAPI 的 POST 请求上传的音频,所以如果我使用来自 fastapi 的 UploadFile class 上传 a.wav 音频,我会得到一个 tempfile.SpooledTemporaryFile,我如何调整第一个 function 以适应这种情况.

@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). wave.open function支持object这样的文件,所以可以直接使用UploadFile.file属性(代表SpooledTemporaryFile实例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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