簡體   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?

我有一個 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,
     }

現在我希望音頻文件來自使用 FastAPI 的 POST 請求上傳的音頻,所以如果我使用來自 fastapi 的 UploadFile class 上傳 a.wav 音頻,我會得到一個 tempfile.SpooledTemporaryFile,我如何調整第一個 function 以適應這種情況.

@app.post(path="/upload-audios/")
async def upload_audios(audios: list[UploadFile] = File(...)):
   pass

wave.open function支持object這樣的文件,所以可以直接使用UploadFile.file屬性(代表SpooledTemporaryFile實例)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM